<?
//classe di gestione servizi - categorie
class category {

	var $cid;
	var $titolo;
	var $desc;
	var $lang;
	var $idfather;
	var $ordine;
	var $attivo;
	var $tagtitle;
	var $tagkey;
	var $tagdesc;
	var $metatitle;
	var $metakey;
	var $metadesc;
	var $hidden;

	function category($cid,$titolo="",$desc="",$lang="",$idfather=0, $tagtitle="", $tagkey="", $tagdesc="", $metatitle="", $metakey="", $metadesc="", $hidden="")  {
		global $conn;
		if($cid != "") {
			$qry = "SELECT * FROM categorie WHERE cid='$cid';";
			$result = $conn->Execute($qry);
			$this->cid = $cid;
			list($cid,$titolo,$desc,$lang,$idfather,$ordine,$attivo,$tagtitle, $tagkey, $tagdesc, $metatitle, $metakey, $metadesc, $hidden) = @array_values($result->FetchRow());
		 $result->Close();
		 $this->ordine = $ordine;
		} else {
			$this->cid = $cid;
			$res_max = $conn->Execute("SELECT MAX(ordine) as maxordine FROM categorie WHERE lang='$lang' AND idfather='$idfather';");
			$maxordine = $res_max->Fields("maxordine");
		 if(is_null($maxordine))
		 $this->ordine = 0;
		 else
		 $this->ordine = $maxordine + 1;
		 $res_max->Close();
		}
		$this->titolo = $titolo;
		$this->desc = $desc;
		$this->lang = $lang;
		$this->idfather = $idfather;
		$this->attivo = $attivo;
		$this->tagtitle = $tagtitle;
		$this->tagkey = $tagkey;
		$this->tagdesc = $tagdesc;
		$this->metatitle = $metatitle;
		$this->metakey = $metakey;
		$this->metadesc = $metadesc;
		$this->hidden = $hidden;
	}

	function save()  {
		global $conn;
		$this->desc = str_replace("\r","<br>",$this->desc);
		$qry = "INSERT INTO categorie VALUES(NULL,'$this->titolo', '$this->desc', '$this->lang', '$this->idfather','$this->ordine','y', '$this->tagtitle','$this->tagkey','$this->tagdesc','$this->metatitle','$this->metakey','$this->metadesc','$this->hidden');";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs) {
			$this->idservizio = $conn->Insert_ID();
			$error = 0;
		} else {
			$error = "Inserimento errato.<br>Ripetere l'operazione.";
		}
		return $error;
	}

	function update($titolo,$desc,$tagtitle, $tagkey, $tagdesc, $metatitle, $metakey, $metadesc, $hidden)  {
		global $conn;
		$qry = "UPDATE categorie SET titolo='$titolo',descrizione='$desc',tagtitle='$tagtitle', tagkey='$tagkey', tagdesc='$tagdesc', metatitle='$metatitle', metakey='$metakey',metadesc='$metadesc',hidden='$hidden' WHERE cid='$this->cid';";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs) {
			$this->titolo = $titolo;
			$this->desc = $desc;
			$error = 0;
		}  else  {
			$error = "Errore nell'operazione.";
		}
		return $error;
	}

	function delete()  {
		global $conn;
		//controllo la presenza di elementi-prodotti
		$qry_prod = "SELECT idarticolo FROM articoli_new WHERE cid='$this->cid';";
		$res_prod = $conn->Execute($qry_prod);
		$num_prod = $res_prod->RecordCount();
		if($num_prod > 0) {
			$error = "Impossibile cancellare la categoria, contiene articoli. E' necessario eliminarli prima!";
			return $error;
		}
		$res_prod->Close();
		//controllo la presenza di sottocategorie
		$qry_cat = "SELECT cid FROM categorie WHERE idfather='$this->cid';";
		$res_cat = $conn->Execute($qry_cat);
		$num_cat = $res_cat->RecordCount();
		if($num_cat > 0) {
			$error = "Impossibile cancellare la categoria, contiene sottocategorie. E' necessario eliminarle prima!";
			return $error;
		}
		$res_prod->Close();
		$qry = "DELETE FROM categorie WHERE cid='$this->cid';";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
		}  else  {
			$error = "Errore nell'operazione.";
		}
		return $error;
	}

	function up()  {
		global $conn;
		$ordineup = $this->ordine-1;
		$qryup = "UPDATE categorie SET ordine=ordine+1 WHERE ordine='$ordineup' AND lang='$this->lang' AND idfather='$this->idfather';";
		$rs = $conn->Execute($qryup);
		if ($rs) {
			$qry = "UPDATE categorie SET ordine=ordine-1 WHERE ordine='$this->ordine' AND lang='$this->lang' AND cid='$this->cid' AND idfather='$this->idfather';";
			$rs = $conn->Execute($qry);
			if($rs) {
				$error = "0";
			}  else  {
				$error = "Errore nell'operazione.";
			}
		}  else
		$error = "Errore nell'operazione.";
		$rs->Close();
		return $error;
	}

	function down()  {
		global $conn;
		$ordinedown = $this->ordine + 1;
		$qrydown = "UPDATE categorie SET ordine=ordine-1 WHERE ordine='$ordinedown' AND lang='$this->lang' AND idfather='$this->idfather';";
		$rs = $conn->Execute($qrydown);
		if ($rs) {
			$qry = "UPDATE categorie SET ordine=ordine+1 WHERE ordine='$this->ordine' AND lang='$this->lang' AND cid='$this->cid' AND idfather='$this->idfather';";
			$rs = $conn->Execute($qry);
			if($rs) {
				$error = "0";
			}  else  {
				$error = "Errore nell'operazione.";
			}
		}  else
		$error = "Errore nell'operazione.";
		$rs->Close();
		return $error;
	}

	function disactive()  {
		global $conn;
		$qry = "UPDATE categorie SET attivo='n' WHERE cid=$this->cid;";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function active()  {
		global $conn;
		$qry = "UPDATE categorie SET attivo='y' WHERE cid=$this->cid;";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function getParent($cid,$result)  {
		global $conn;
		$newCat = new category($cid);
		if($newCat->idfather!=0)  {
			$result = "$result-".$newCat->idfather;
			$result = category::getParent($newCat->idfather,$result);
		}
		return $result;
	}


	function getChild($cid,$result)  {
		global $conn;
		$qry = "SELECT cid FROM categorie WHERE idfather=$cid AND attivo='y';";
		$rs = $conn->Execute($qry);
		if($rs)  {
			while(!$rs->EOF)  {
				$result = "$result,".$rs->Fields("cid");
				$result = category::getChild($rs->Fields("cid"),$result);
				$rs->MoveNext();
			}
			$rs->Close();
		}
		return $result;
	}

	function listCat($percorso)  {
		global $conn,$currentpage;
		$rmax = $conn->Execute("SELECT MAX(ordine) as maxordine FROM categorie WHERE lang='$lang' AND idfather='$this->cid';");
		$maxordine = $rmax->Fields("maxordine");
		$rmax->Close();
		$qry = "SELECT cid,titolo,ordine,attivo FROM categorie WHERE idfather='$this->cid' ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$content = "<table width=400 class=content cellpadding=2>";
			while(!$rs->EOF)  {
				$cid = $rs->Fields("cid");
				if($rs->Fields("ordine") == "0")
				$up = "&nbsp;";
				else
				$up = "<a href=product_new.php?op=up&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."><img src=imgs/ico_up.gif width=16 height=16 alt=\"sposta su\" border=0></a>";
				if($rs->Fields("ordine") == $maxordine)
				$down = "&nbsp;";
				else
				$down = "<a href=product_new.php?op=down&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."><img src=imgs/ico_down.gif width=16 height=16 alt=\"sposta gi�\" border=0></a>";
				#########################################################################################
				if($rs->Fields("attivo") == "y")
				$semaforo = "<a href=\"product_new.php?op=disactivecat&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/ico_green.jpg\" border=0 alt=Disattiva></a>";
				else
				$semaforo = "<a href=\"product_new.php?op=activecat&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/ico_red.jpg\" border=0 alt=Attiva></a>";
				#########################################################################################
				$content .= "<tr>
		    				<td width=30 align=center><img src=\"imgs/folder.gif\" width=20></td>
		    				<td width=300><a href=\"product_new.php?cid=".$rs->Fields("cid")."&op=product&percorso=".urlencode($percorso."/".$rs->Fields("titolo"))."\">".$rs->Fields("titolo")."</a></td>
		    				<td>$up</td>
		    				<td>$down</td>
		    				<td align=center><a href=\"product_new.php?op=del&cid=".$rs->Fields("cid")."&currentpage=".urlencode($percorso)."\" onclick=\"return confirm('Sei sicuro di voler eliminare la categoria ?');\"><img src=imgs/ico_delete.gif width=16 height=16 alt=\"elimina\" border=0></a></td>
		    				<td>$semaforo</td>
						 </tr>";
				$rs->MoveNext();
			}
			$content .= "</table>";
		}
		return $content;
	}

	function listProd($currentpage)  {
		global $conn,$percorso;
		//estrazione prodotti
		$content .= "<table width=100% class=content cellpadding=3 cellspacing=0 border=0>
				 <tr>
				   <td colspan=17 style=\"color:red\">Per modificare gli importi cliccare sul valore da aggiornare, fare la modifica e cliccare fuori dalla tabella.</td>
				 </tr>
				 <tr>
				   	<td width=20>&nbsp;</td>
				   	<td width=350><b>Articolo</b></td>
				   	<td width=50><b>Codice</b></td>
				   	<td width=50><b>Prezzo(&euro;)</b></td>
				   	<td width=50><b>Scontato(&euro;)</b></td>
				   	<td width=50><b>Costo IVA incl.(&euro;)</b></td>
				   	<td width=50><b>Spediz.(&euro;)</b></td>
				   	<td width=50><b>Sec. Prod.(&euro;)</b></td>
				   	<td width=50><b>Ricarico.(%)</b></td>
				   	<td width=20><b>Min.</b></td>
				   	<td width=20><b>Disp.</b></td>
				   	<td width=30><b>Vetr.</b></td>
				   	<td width=30><b>Prom.</b></td>
				   	<td width=30><b>Nov.</b></td>
				   	<td width=50><b>Fornitore</b></td>
				   	<td width=50><b>Produttore</b></td>
					<td></td>
				   	<td></td>
				   	<td></td>
				   	<td></td>
				   	<td></td>
				   	<td></td>
				   	<td></td>
				   </tr>";
		$rmax = $conn->Execute("SELECT MAX(ordine) as maxordine FROM articoli_new WHERE lang='$lang' AND cid='$this->cid';");
		$maxordine = $rmax->Fields("maxordine");
		$rmax->Close();
		$qry_page = "SELECT idarticolo,titolo1,ordine,attivo,banner,prezzo1,prezzo2,spedizione,spedizione2,minimo,disp,codice,costo,fornitore,vetrina,promozione,novita,produttore,image_tmb,vetrinacat FROM articoli_new WHERE cid='$this->cid' AND lang='$this->lang' ORDER BY ordine ASC;";
		$rs = $conn->Execute($qry_page);
		if($rs->RecordCount() > 0)  {
			while(list($idarticolo,$titolo1,$ordine,$attivo,$banner,$prezzo1,$prezzo2,$spedizione,$spedizione2,$minimo,$disp,$codice,$costo,$fornitore,$vetrina,$promozione,$novita,$produttore,$image_tmb,$vetrinacat) = @array_values($rs->FetchRow()))  {
				if($ordine == "0")
				$up = "&nbsp;";
				else
				$up = "<a href=product_new.php?op=up_art&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."><img src=imgs/ico_up.gif width=16 height=16 alt=\"sposta su\" border=0></a>";
				if($ordine == $maxordine)
				$down = "&nbsp;";
				else
				$down = "<a href=product_new.php?op=down_art&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."><img src=imgs/ico_down.gif width=16 height=16 alt=\"sposta gi�\" border=0></a>";
				#########################################################################################
				if($attivo == "y")
				$semaforo = "<a href=\"product_new.php?op=disactive&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/ico_green.jpg\" border=0 alt=Disattiva></a>";
				else
				$semaforo = "<a href=\"product_new.php?op=active&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/ico_red.jpg\" border=0 alt=Attiva></a>";
				#########################################################################################
				if($banner == "y")
				$banner = "<a href=\"product_new.php?op=bannerOut&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/banner.jpg\" border=0 alt=\"In banner destra\"></a>";
				else
				$banner = "<a href=\"product_new.php?op=bannerIn&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/nobanner.jpg\" border=0 alt=\"No banner destra\"></a>";
				#########################################################################################
				if($vetrinacat > 0)
				$vetrinacat_link = "<a href=\"product_new.php?op=vetrinaOut&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><div style=\"width:16px;height:16px;background-color:green;color:#ffffff;text-align:center;font-weight:bold;\">V</div></a>";
				else
				$vetrinacat_link = "<a href=\"product_new.php?op=vetrinaIn&idarticolo=$idarticolo&cid=$this->cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><div style=\"width:16px;height:16px;background-color:red;color:#ffffff;text-align:center;font-weight:bold;\">V</div></a>";				
				#######################################################################################
				if($fornitore=="") $fornitore = "&nbsp;";
				if($produttore=="") $produttore = "&nbsp;";
				$costo > 0 ? $ricarico = ((($prezzo2 + $spedizione) / $costo) - 1)*100 : $ricarico=0;
				if($image_tmb!="") {
					file_exists("imgs_prodotti/$idarticolo/$image_tmb") ? $image = '<img src="imgs_prodotti/'.$idarticolo.'/'.$image_tmb.'" />' : $image = '<img src="../immagini-piscine/'.$image_tmb.'" />';
				} else {
					$image = '';
				}
				$content .= "<tr>
				   <td class=content width=20>$image</td>
				   <td><div id=\"titolo1_$idarticolo\" onClick=\"ajax_edit('titolo1_$idarticolo')\">$titolo1</div></td>
				   <td><div id=\"codice_$idarticolo\" onClick=\"ajax_edit('codice_$idarticolo')\">$codice</div></td>
				   <td><div id=\"prezzo1_$idarticolo\" onClick=\"ajax_edit('prezzo1_$idarticolo')\">$prezzo1</div></td>
				   	<td><div id=\"prezzo2_$idarticolo\" onClick=\"ajax_edit('prezzo2_$idarticolo')\">$prezzo2</div></td>
				   	<td><div id=\"costo_$idarticolo\" onClick=\"ajax_edit('costo_$idarticolo')\">$costo</div></td>
				   	<td><div id=\"spedizione_$idarticolo\" onClick=\"ajax_edit('spedizione_$idarticolo')\">$spedizione</div></td>
				   	<td><div id=\"spedizione2_$idarticolo\" onClick=\"ajax_edit('spedizione2_$idarticolo')\">$spedizione2</div></td>
				   	<td><div id=\"ricarico_$idarticolo\" >".number_format($ricarico,2)."</div></td>
				   	<td><div id=\"minimo_$idarticolo\" onClick=\"ajax_edit('minimo_$idarticolo')\">$minimo</div></td>
				   	<td><div id=\"disp_$idarticolo\" onClick=\"ajax_edit('disp_$idarticolo')\">$disp</div></td>
				   	<td><div id=\"vetrina_$idarticolo\" onClick=\"ajax_edit('vetrina_$idarticolo')\">$vetrina</div></td>
				   	<td><div id=\"promozione_$idarticolo\" onClick=\"ajax_edit('promozione_$idarticolo')\">$promozione</div></td>
				   	<td><div id=\"novita_$idarticolo\" onClick=\"ajax_edit('novita_$idarticolo')\">$novita</div></td>
				   	<td><div id=\"fornitore_$idarticolo\" onClick=\"ajax_edit('fornitore_$idarticolo')\">$fornitore</div></td>
				   	<td><div id=\"produttore_$idarticolo\" onClick=\"ajax_edit('produttore_$idarticolo')\">$produttore</div></td>
				   <td bgcolor=#DFDFDF>$up</td>
				   <td bgcolor=#DFDFDF>$down</td>
				   <td width=20px bgcolor=\"#DFDFDF\"><a href=\"product_new.php?cid=$this->cid&op=product&idarticolo=$idarticolo&percorso=$percorso\"><img src=imgs/ico_edit.gif width=16 height=16 alt=\"modifica\" border=0></a></td>
				   <td width=20px bgcolor=\"#DFDFDF\"><a href=\"product_new.php?op=del_art&idarticolo=$idarticolo&currentpage=$currentpage&percorso=".urlencode($percorso)."\" onclick=\"return confirm('Sei sicuro di voler eliminare l\'articolo cliccato?');\"><img src=imgs/ico_delete.gif width=16 height=16 alt=\"elimina\" border=0></a></td>
				   <td width=20px bgcolor=\"#DFDFDF\"><a href=\"product_new.php?op=duplica&idarticolo=$idarticolo&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=imgs/duplica.jpg width=16 height=16 alt=\"Duplica\" border=0></a></td>
				   <td width=50 bgcolor=#DFDFDF>$banner</td>
				   <td width=20 bgcolor=#DFDFDF>$semaforo</td>
				   <td width=20 bgcolor=#DFDFDF>$vetrinacat_link</td>";
				$content .= "</tr>";
			}
		}
		$rs->Close();
		$content .= "</table>";
		return $content;
	}

	function menusx($cid2="")  {
		global $conn,$lang;
		$qry = "SELECT cid,titolo FROM categorie WHERE idfather='0' AND lang='$lang' AND attivo='y' ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		$content = '<div style="z-index:1000"><ul class="jd_menu_vertical jd_menu_slate">';
		if($rs)  {
			$i = 0;
			while(!$rs->EOF)  {
				if($i < 4)  {
					switch($i)  {
			   case 0:
			   	$classid1 = "msx_piscine";
			   	$classid2 = "msx_piscine-sub";
			   	$classid3 = "msx_piscine-sub2";
			   	break;

			   case 1:
			   	$classid1 = "msx_giardino";
			   	$classid2 = "msx_giardino-sub";
			   	$classid3 = "msx_giardino-sub2";
			   	break;

			   case 2:
			   	$classid1 = "msx_casa";
			   	$classid2 = "msx_casa-sub";
			   	$classid3 = "msx_casa-sub2";
			   	break;

			   case 3:
			   	$classid1 = "msx_sport";
			   	$classid2 = "msx_sport-sub";
			   	$classid3 = "msx_sport-sub2";
			   	break;

			   case 4:
			   	$classid1 = "msx_fit";
			   	$classid2 = "msx_fit-sub";
			   	$classid3 = "msx_fit-sub2";
			   	break;
					}
					$content .= '<li id="'.$classid1.'">'.$rs->Fields("titolo");
					$cid1 = $rs->Fields("cid");
					//sottocategorie
					$qry = "SELECT cid,titolo FROM categorie WHERE idfather='$cid1' AND attivo='y' ORDER BY ordine;";
					$sottocat = $conn->Execute($qry);
					if($sottocat)  {
						$content .= '<ul>';
				  while(!$sottocat->EOF)  {
				  	$newCat = new category($sottocat->Fields("cid"));
				  	$num = $newCat->getNumArticoli();
				  	$content .= '<li id="'.$classid2.'"><a href="webproduct.php?cid1='.$cid1.'&cid2='.$sottocat->Fields("cid").'">'.$sottocat->Fields("titolo").'('.$num.')</a>';
					  $qry = "SELECT cid,titolo FROM categorie WHERE idfather=".$sottocat->Fields("cid")." AND attivo='y' ORDER BY ordine;";
					  $sscat = $conn->Execute($qry);
					  if($sscat)  {
					  	$content .= "<ul>";
					  	while(!$sscat->EOF)  {
					  		$qry = "SELECT COUNT(idarticolo) as num FROM articoli_new WHERE cid='".$sscat->Fields("cid")."' AND attivo='y';";
					  		$rs_num = $conn->Execute($qry);
					  		$num = $rs_num->Fields("num");
					  		$rs_num->Close();
					  		$content .= '<li id="'.$classid3.'"><a href="webproduct.php?cid1='.$cid1.'&cid2='.$sottocat->Fields("cid").'&cid3='.$sscat->Fields("cid").'">'.$sscat->Fields("titolo").'('.$num.')</a></li>';
					  		$sscat->MoveNext();
					  	}
					  	$sscat->Close();
					  	$content .= "</ul>";
					  }
					  $content .= '</li>';
					  $sottocat->MoveNext();
				  }
				  $sottocat->Close();
				  $content .= '</ul>';
					}
					$content .= '</li>';
				}
				$rs->MoveNext();
				$i++;
			}
			$rs->Close();
		}
		$content .= '</ul></div>';
		return $content;
	}

	function menuSxNew($cid2="")  {
		global $conn,$lang;
		$qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather=$cid2 AND attivo='y' ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		$content[0] = '<ul class="jd_menu_vertical jd_menu_slate">';
		if($rs)  {
			while(!$rs->EOF)  {
				switch($cid2)  {
					case 2:
						$classid1 = "msx_piscine";
						$classid2 = "msx_piscine-sub";
						$classid3 = "msx_piscine-sub2";
						$folder = "piscine";
			   break;

					case 3:
						$classid1 = "msx_giardino";
						$classid2 = "msx_giardino-sub";
						$classid3 = "msx_giardino-sub2";
						$folder = "giardino";
			   break;

					case 267:
						$classid1 = "msx_casa";
						$classid2 = "msx_casa-sub";
						$classid3 = "msx_casa-sub2";
						$folder = "casa";
			   break;

					case 4:
						$classid1 = "msx_sport";
						$classid2 = "msx_sport-sub";
						$classid3 = "msx_sport-sub2";
						$folder = "sport-fitness";
			   break;
			 }
			 $cid1 = $rs->Fields("cid");
			 $permalink = fromTitToUrl($rs->Fields("hidden"));
			 //$content[0] .= '<li id="'.$classid2.'"><a href="javascript:;" onMouseOver="getMenu('.$cid2.','.$cid1.')">'.$rs->Fields("titolo").'</a><ul id="cat'.$cid1.'"></ul>';
			 $content[0] .= '<li id="'.$classid2.'"><a href="/'.$permalink.'/">'.$rs->Fields("titolo").'</a>';
			 //sottocategorie
			 $qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather='$cid1' AND attivo='y' ORDER BY ordine;";
			 $sottocat = $conn->Execute($qry);
			 if($sottocat)  {
			 	$content[0] .= '<ul>';
			 	while(!$sottocat->EOF)  {
			 		$newCat = new category($sottocat->Fields("cid"));
			 		$permalink = fromTitToUrl($sottocat->Fields("hidden"));
			 		$content[0] .= '<li id="'.$classid3.'" style="white-space: nowrap;"><a href="/'.$permalink.'/">'.$sottocat->Fields("titolo").'</a></li>';
			 		$sottocat->MoveNext();
			 	}
			 	$sottocat->Close();
				 $content[0] .= '</ul>';
				}
			 $content[0] .= '</li>';
			 $rs->MoveNext();
			}
			$rs->Close();
		}
		$content[0] .= '</ul>';
		return $content;
	}

	function menuSxNew2($cid2="")  {
		global $conn,$lang;
		$qry = "SELECT cid,titolo FROM categorie WHERE idfather=$cid2 AND attivo='y' ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		$content[0] = '<div style="z-index:1000"><ul class="jd_menu_vertical jd_menu_slate">';
		if($rs)  {
			while(!$rs->EOF)  {
				switch($cid2)  {
					case 2:
						$classid1 = "msx_piscine";
						$classid2 = "msx_piscine-sub";
						$classid3 = "msx_piscine-sub2";
						$folder = "piscine";
			   break;

					case 3:
						$classid1 = "msx_giardino";
						$classid2 = "msx_giardino-sub";
						$classid3 = "msx_giardino-sub2";
						$folder = "giardino";
			   break;

					case 267:
						$classid1 = "msx_casa";
						$classid2 = "msx_casa-sub";
						$classid3 = "msx_casa-sub2";
						$folder = "casa";
			   break;

					case 4:
						$classid1 = "msx_sport";
						$classid2 = "msx_sport-sub";
						$classid3 = "msx_sport-sub2";
						$folder = "sport-fitness";
			   break;
			 }
			 $cid1 = $rs->Fields("cid");
			 //$content[0] .= '<li id="'.$classid2.'"><a href="javascript:;" onMouseOver="getMenu('.$cid2.','.$cid1.')">'.$rs->Fields("titolo").'</a><ul id="cat'.$cid1.'"></ul>';
			 $content[0] .= '<li id="'.$classid2.'"><a href="http://www.bsvillage.com/'.$folder.'/'.$cid2.'-'.$cid1.'.html">'.$rs->Fields("titolo").'</a>';
			 //sottocategorie
			 $qry = "SELECT cid,titolo FROM categorie WHERE idfather='$cid1' AND attivo='y' ORDER BY ordine;";
			 $sottocat = $conn->Execute($qry);
			 if($sottocat)  {
			 	$content[0] .= '<ul>';
			 	while(!$sottocat->EOF)  {
			 		$newCat = new category($sottocat->Fields("cid"));
			 		$num = $newCat->getNumArticoli();
			 		$content[0] .= '<li id="'.$classid3.'" style="white-space: nowrap;"><a href="http://www.bsvillage.com/'.$folder.'/'.$cid2.'-'.$cid1.'-'.$sottocat->Fields("cid").'.html">'.$sottocat->Fields("titolo").'('.$num.')</a></li>';
			 		$sottocat->MoveNext();
			 	}
			 	$sottocat->Close();
				 $content[0] .= '</ul>';
				}
			 $content[0] .= '</li>';
			 $rs->MoveNext();
			}
			$rs->Close();
		}
		$content[0] .= '</ul></div>';
		return $content;
	}

	function getMenu($cid1,$cid2)  {
		global $conn,$lang;
		switch($cid1)  {
			case 2:
				$classid1 = "msx_piscine";
				$classid2 = "msx_piscine-sub";
				$classid3 = "msx_piscine-sub2";
				$folder = "piscine";
				break;

			case 3:
				$classid1 = "msx_giardino";
				$classid2 = "msx_giardino-sub";
				$classid3 = "msx_giardino-sub2";
				$folder = "giardino";
				break;

			case 267:
				$classid1 = "msx_casa";
				$classid2 = "msx_casa-sub";
				$classid3 = "msx_casa-sub2";
				$folder = "casa";
				break;

			case 4:
				$classid1 = "msx_sport";
				$classid2 = "msx_sport-sub";
				$classid3 = "msx_sport-sub2";
				$folder = "sport-fitness";
				break;
		}
		$qry = "SELECT cid,titolo FROM categorie WHERE idfather=$cid1 AND attivo='y' ORDER BY ordine;";
		$sottocat = $conn->Execute($qry);
		$json = '{"count":';
		if($sottocat->RecordCount()>0)  {
			$first = false;
			$json .= $sottocat->RecordCount().',"id":"'.$classid3.'","folder":"'.$folder.'","record":[';
			while(!$sottocat->EOF)  {
				$newCat = new category($sottocat->Fields("cid"));
				$num = $newCat->getNumArticoli();
				$first ? $json.=',' : $first=true;
				$json .= '{"cid":'.$sottocat->Fields("cid").', "href":"http://www.bsvillage.com/'.$folder.'/'.$cid2.'-'.$cid1.'-'.$sottocat->Fields("cid").'.html","titolo":"'.htmlentities($sottocat->Fields("titolo")).'('.$num.')"}';
				$sottocat->MoveNext();
			}
			$sottocat->Close();
			$json .= ']';
		} else
		$json .= '0';
		$json .= '}';
		return $json;
	}

	function getMenuMaps($cid)  {
		global $conn,$lang;
		switch($cid)  {
			case 2:
				$folder = "piscine";
				break;

			case 3:
				$folder = "giardino";
				break;

			case 267:
				$folder = "casa";
				break;

			case 4:
				$folder = "sport-fitness";
				break;
		}
		$qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather=$cid AND attivo='y' ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$menu = '';
			while(!$rs->EOF) {
				$cid1 = $rs->Fields("cid");
				$permalink = fromTitToUrl($rs->Fields("hidden"));
				$menu .= '<p><a class="tit02" href="/'.$permalink.'/">'.$rs->Fields("titolo").'</a></p>';
				$qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather=".$rs->Fields("cid")." AND attivo='y' ORDER BY ordine;";
				$rs2 = $conn->Execute($qry);
				if($rs2->RecordCount()>0)  {
					while(!$rs2->EOF) {
							$cid2 = $rs2->Fields("cid");
							$permalink2 = fromTitToUrl($rs2->Fields("hidden"));
							$menu .= '<p style="padding-left:10px;"><a class="tit02" href="/'.$permalink.'/'.$permalink2.'/">'.$rs2->Fields("titolo").'</a></p>';
							$rs2->MoveNext();
						}
						$rs2->Close();
				}
				$rs->MoveNext();
			}
			$rs->Close();
		}
		return $menu;
	}

	function getNumArticoli()  {
		global $conn,$lang;
		$list_cid = category::getChild($this->cid,$this->cid);
		//die($list_cid);
		$qry = "SELECT COUNT(idarticolo) as num FROM articoli_new INNER JOIN categorie ON articoli_new.cid=categorie.cid WHERE articoli_new.lang='$lang' AND articoli_new.attivo='y' AND (categorie.cid IN ($list_cid) OR
		idarticolo IN (SELECT idarticolo FROM categorie_correlate WHERE cid=$this->cid));";
		$rs = $conn->Execute($qry);
		if($rs) {
			$num = $rs->Fields("num");
			$rs->Close();
		} else
		$num = 0;
		return $num;
	}

	function json_cat()  {
		global $conn;
		$qry = "SELECT DISTINCT categorie.cid as cid,categorie.titolo as titolo FROM
		 categorie INNER JOIN articoli_new ON categorie.cid=articoli_new.cid WHERE categorie.lang='ita' ORDER BY titolo";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$json = "{'rows':[";
			$rc = false;
			while(!$rs->EOF)  {
				if($rc) $json.=",";
				$json .= "{'cid':'".$rs->Fields("cid")."','titolo':'".htmlentities(addslashes($rs->Fields("titolo")))."'}";
				$rc = true;
			 $rs->MoveNext();
			}
			$json .= "]}";
			$rs->Close();
		}
		return $json;
	}

	function getIconeHome($cid) {
		global $conn;
		$result = '<div style="float:left; clear:both;">';
		$qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather=$cid ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0) {
			while(!$rs->EOF) {
				$permalink = fromTitToUrl($rs->Fields("hidden"));
				if(file_exists($_SERVER['DOCUMENT_ROOT']."/icone-piscine/".$rs->Fields("cid").".jpg"))
				$image = '<a href="/'.$permalink.'/" title="'.$rs->Fields("titolo").'"><img src="/icone-piscine/'.$rs->Fields("cid").'.jpg" alt="'.$rs->Fields("titolo").'"></a>';
				else
				$image = '&nbsp;';
				$result .= '<div class="ico-home">'.$image.'
	       	 				<p><a class="plain" href="/'.$permalink.'/">'.$rs->Fields("titolo").'</a></p>
	       	 </div>';
				$rs->MoveNext();
			}
			$rs->Close();
		}
		$result .= '</div>';
		return $result;
	}

	function saveAttributo($nome,$cid) {
		global $conn;
		$qry = "INSERT INTO attributi_categorie VALUES(NULL,$cid,'$nome');";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs)
		$error = 0;
		else
		$error = "Errore nell'operazione.";
		return $error;
	}

	function updateAttributo($nome,$id) {
		global $conn;
		$qry = "UPDATE attributi_categorie SET nome='$nome' WHERE id=$id;";
		$rs = $conn->Execute($qry);
		if($rs)
		$error = 0;
		else
		$error = "Errore nell'operazione.";
		return $error;
	}

	function deleteAttributo($id) {
		global $conn;
		$qry = "DELETE FROM attributi_categorie WHERE id=$id;";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = 0;
			$rs = $conn->Execute("DELETE FROM attributi_categorie_articoli WHERE id=$id;");
		} else
		$error = "Errore nell'operazione.";
		return $error;
	}

	function getAttributo($id) {
		global $conn;
		$qry = "SELECT nome FROM attributi_categorie WHERE id=$id;";
		return get_json($qry);
	}

	function getAttributi($cid) {
		global $conn;
		$qry = "SELECT id,nome FROM attributi_categorie WHERE cid=$cid ORDER BY nome;";
		return get_json($qry);
	}

	function getId($link) {
		$qry = "SELECT cid FROM categorie WHERE hidden='".fromUrlToTit($link)."' LIMIT 0,1;";
		$rs = esegui_queryRs($qry);
		$id = 0;
		if($rs->RecordCount()>0) {
			$id = $rs->Fields("cid");
			$rs->Close();
		}
		return $id;
	}

	function getSearchMenu() {
		global $conn;
		$elenco = category::getChild(2,"0");
		$qry = "SELECT titolo FROM categorie WHERE lang='ita' AND attivo='y' AND cid IN ($elenco) ORDER BY titolo;";
		$menu = get_json($qry);
		return $menu;
	}

	function getMenuSx($idfather,$cid) {
		global $conn;
		
		if($idfather=="") $idfather = 0;
		
		if ($cid>0) $where = array(" AND cid=$cid", " AND cid<>$cid");
		else $where = array("");
		
		for ($iw=0;$iw<count($where);$iw++) {
			$qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather=$idfather".$where[$iw]." AND attivo='y' ORDER BY titolo, ordine;";
			$rs = esegui_queryRs($qry);
			if($rs->RecordCount() > 0) {
				while(!$rs->EOF) {
					$permalink = fromTitToUrl($rs->Fields("hidden"));
					if($cid==$rs->Fields("cid")) {
						$class1 = "expanded";
						$class2 = "";
					} else {
						$class1 = "";
						$class2 = "collapsed";
					}
					$menu .= '<li class="menu-cat'.($cid==$rs->Fields("cid")?' sel':'').'" id="cat'.$rs->Fields("cid").'"><!--<a class="menuTree '.$class1.'" href="#" onClick="openCategoria(\'menu'.$rs->Fields("cid").'\',this)"></a>-->
					<a class="menuTree '.$class1.'" href="#" onClick=""></a> <blockquote><a href="/'.$permalink.'/">'.$rs->Fields("titolo").'</a></blockquote>';
					
					if($cid == $rs->Fields("cid")) {
						$menu .= '<ul id="menu'.$rs->Fields("cid").'" class="'.$class2.'" style="padding: 5px 0 0 5px;">';
						$qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather=".$rs->Fields("cid")." AND attivo='y' ORDER BY titolo,ordine;";
						$rsf = $conn->Execute($qry);
						if($rsf->RecordCount()>0) {
							while(!$rsf->EOF) {
								$permalink2 = fromTitToUrl($rsf->Fields("hidden"));
								
								$qryCheckProd = "SELECT COUNT(idarticolo) as num FROM articoli_new WHERE cid='".$rsf->Fields("cid")."' AND attivo='y';";
								$rsCheckProd = $conn->Execute($qryCheckProd);
								$numProd = $rsCheckProd->Fields("num");
								$rsCheckProd->Close();
								
								$qryCheckCatCorr = "SELECT COUNT(idarticolo) as num FROM categorie_correlate WHERE cid='".$rsf->Fields("cid")."'";
								$rsCheckCatCorr = $conn->Execute($qryCheckCatCorr);
								$numCatCorr = $rsCheckCatCorr->Fields("num");
								$rsCheckCatCorr->Close();
								
								if($numProd>0 || $numCatCorr>0) {
									//if($cid > 0)
									/**/
									if (!isset($_GET['id'])) {
										$qry = "SELECT cid FROM categorie WHERE hidden='".fromUrlToTit($_GET['link'])."' LIMIT 0,1;";
										$rsSubmenu = esegui_queryRs($qry);
										$id = 0;
									}
									if(!isset($_GET['id']) && @$rsSubmenu->RecordCount()>0) {
										$id = $rsSubmenu->Fields("cid");
										$rsSubmenu->Close();
									} else {
										$qry = "SELECT cid FROM articoli_new WHERE idarticolo='".$_GET['id']."' LIMIT 0,1;";
										$rsSubmenu = esegui_queryRs($qry);
										if($rsSubmenu->RecordCount()>0) {
											$id = $rsSubmenu->Fields("cid");
											$rsSubmenu->Close();
										} else {
											$id = isset($_GET['cid3'])?$_GET['cid3']:0;
										}
									}
									/**/
									$menu .= '<li class="submenu-cat'.($rsf->Fields("cid")==$id?" sel":"").'" id="cat'.$rsf->Fields("cid").'"><a href="/'.$permalink.'/'.$permalink2.'/">'.$rsf->Fields("titolo").'</a></li>';
								}
								$rsf->MoveNext();
								
							}
							//$menu .= '</ul></li>';
						} //else
						$menu .= '</ul>';
					}
					$menu .= '</li>';
					$rs->MoveNext();
				}
				$rs->Close();
			}
		} 
		return $menu;
	}
	
	function getNavbarAdmin($cid,$result)  {
	    global $conn,$lang;
	    	  $newcid = new category($cid);
	    	  if($newcid->idfather != "0" && $newcid->idfather != "")  {
	    	      $father = new category($newcid->idfather);
				  $result = '<a href="product_new.php?cid='.$father->cid.'&op=product">'.$father->titolo.'</a> / '.$result;
				  $result = category::getNavbarAdmin($newcid->idfather,$result);
			  }	  
		return $result;  
    }
    
	function getPathCategoria($cid,$result)  {
	    global $conn,$lang;
	    	  $newcid = new category($cid);
	    	  if($newcid->idfather != "0" && $newcid->idfather != "")  {
	    	      $father = new category($newcid->idfather);
				  $result = $father->titolo.' / '.$result;
				  $result = category::getPathCategoria($newcid->idfather,$result);
			  }	  
		return $result;  
    }
  
    function getCategorieFull($cids=array()) {
    	global $conn;
    	$qry = "SELECT DISTINCT c.cid as cid,c.titolo AS cat FROM `categorie` c WHERE c.idfather=2 ORDER BY titolo;";
    	$rs = $conn->Execute($qry);
    	if($rs->RecordCount()>0) {
    		$result = '';
    		while(!$rs->EOF) {
    			$result .= '<option value="'.$rs->Fields("cid").'"';
    			if(in_array($rs->Fields("cid"),$cids)) $result .= ' selected';
    			$result .= '>'.category::getPathCategoria($rs->Fields("cid"),$rs->Fields("cat")).'</option>';
    			$rs->MoveNext();
    		}
    		$rs->Close();
    	}
    	return $result;
    }
    
	function getSottoCategorie($cids=array()) {
    	global $conn;
    	$qry = "SELECT DISTINCT c.cid as cid,c.titolo AS cat FROM `categorie` c 
    	LEFT JOIN articoli_new a ON c.cid=a.cid WHERE a.giardino=0 ORDER BY titolo;";
    	$rs = $conn->Execute($qry);
    	if($rs->RecordCount()>0) {
    		$result = '';
    		while(!$rs->EOF) {
    			$result .= '<option value="'.$rs->Fields("cid").'"';
    			if(in_array($rs->Fields("cid"),$cids)) $result .= ' selected';
    			$result .= '>'.category::getPathCategoria($rs->Fields("cid"),$rs->Fields("cat")).'</option>';
    			$rs->MoveNext();
    		}
    		$rs->Close();
    	}
    	return $result;
    }
}

//classe di gestione prodotti - articoli

class articoli  {

	var $idarticolo;
	var $cid;
	var $codice;
	var $titolo1;
	var $titolo2;
	var $desc;
	var $image_tmb;
	var $image;
	var $image_big;
	var $prezzo1;
	var $prezzo2;
	var $spedizione;
	var $spedizione2;
	var $promozione;
	var $vetrina;
	var $novita;
	var $minimo;
	var $attivo;
	var $lang;
	var $ordine;
	var $peso;
	var $video;
	var $scheda;
	var $hit;
	var $disp;
	var $banner;
	var $tagtitle;
	var $tagkey;
	var $tagdesc;
	var $metatitle;
	var $metakey;
	var $metadesc;
	var $hidden;
	var $correlato1;
	var $correlato2;
	var $correlato3;
	var $import;
	var $fornitore;
	var $costo;
	var $giardino;
	var $produttore;
	var $vertinacat;

	function articoli($idarticolo,$cid="",$codice="",$titolo1="",$titolo2="",$desc="",$image_tmb="",$image="",$image_big="",$prezzo1="",$prezzo2="",$spedizione="",$spedizione2="",$promozione="",$vetrina="",$novita="",$minimo="",$lang="",$peso="",$video="",$scheda="",$disp="",$banner="", $tagtitle="", $tagkey="", $tagdesc="", $metatitle="", $metakey="", $metadesc="", $hidden="",$correlato1="",$correlato2="",$correlato3="",$import="",$fornitore="",$costo="",$giardino=0,$produttore="")  {
		global $conn;
		if($idarticolo == "")  {
			$this->idarticolo = "";
			$res_max = $conn->Execute("SELECT MAX(ordine) as maxordine FROM articoli_new WHERE lang='$lang' AND cid='$cid';");
			$maxordine = $res_max->Fields("maxordine");
		 if(is_null($maxordine))
		 $this->ordine = 0;
		 else
		 $this->ordine = $maxordine + 1;
		 $res_max->Close();
		 if($minimo < 1 || $minimo == "")
		 $minimo = 1;
		}  else  {
			$qry = "SELECT * FROM articoli_new WHERE idarticolo='$idarticolo';";
			$result = $conn->Execute($qry);
			list($idarticolo,$cid,$codice,$titolo1,$titolo2,$desc,$image_tmb,$image,$image_big,$prezzo1,$prezzo2,$spedizione,$spedizione2,$promozione,$vetrina,$novita,$minimo,$attivo,$lang,$ordine,$peso,$video,$scheda,$hit,$disp,$banner,$tagtitle, $tagkey, $tagdesc, $metatitle, $metakey, $metadesc, $hidden,$correlato1,$correlato2,$correlato3,$import,$fornitore,$costo,$giardino,$produttore,$vetrinacat) = @array_values($result->FetchRow());
		 $this->idarticolo = $idarticolo;
		 $result->Close();
		 $this->ordine = $ordine;
		 $this->hit = $hit;
		}
		$this->cid = $cid;
		$this->codice = $codice;
		$this->titolo1 = $titolo1;
		$this->titolo2 = $titolo2;
		$this->desc = $desc;
		$this->image_tmb = $image_tmb;
		$this->image = $image;
		$this->image_big = $image_big;
		$this->prezzo1 = $prezzo1;
		$this->prezzo2 = $prezzo2;
		$this->spedizione = $spedizione;
		$this->spedizione2 = $spedizione2;
		$this->promozione = $promozione;
		$this->vetrina = $vetrina;
		$this->novita = $novita;
		$this->minimo = $minimo;
		$this->attivo = $attivo;
		$this->anno = $prezzo2;
		$this->lang = $lang;
		$this->peso = $peso;
		$this->video = $video;
		$this->scheda = $scheda;
		$this->disp = $disp;
		$this->banner = $banner;
		$this->tagtitle = $tagtitle;
		$this->tagkey = $tagkey;
		$this->tagdesc = $tagdesc;
		$this->metatitle = $metatitle;
		$this->metakey = $metakey;
		$this->metadesc = $metadesc;
		$this->hidden = $hidden;
		$this->correlato1 = $correlato1;
		$this->correlato2 = $correlato2;
		$this->correlato3 = $correlato3;
		$this->import = $import;
		$this->fornitore = $fornitore;
		$this->costo = $costo;
		$this->giardino = $giardino;
		$this->produttore = $produttore;
		$this->vertinacat = $vetrinacat;
	}

	function save($varianti=array())  {
		error_reporting(E_WARNING);
		global $conn, $path_image, $path_image_ftp, $path_tmp, $max_size_image, $ftp_host,$ftp_username, $ftp_pwd, $_POST;
		$error = "";
		if($this->idarticolo != "") {
			$himage_tmb = $this->image_tmb;
			$himage = $this->image;
			$himage_big = $this->image_big;
			$this->titolo1 = mysql_real_escape_string($this->titolo1);
			$this->titolo2 = mysql_real_escape_string($this->titolo2);
			$this->desc = mysql_real_escape_string($this->desc);
			$this->scheda = mysql_real_escape_string($this->scheda);
			$this->tagtitle = mysql_real_escape_string($this->tagtitle);
			$this->tagkey = mysql_real_escape_string($this->tagkey);
			$this->tagdesc = mysql_real_escape_string($this->tagdesc);
			$this->metatitle = mysql_real_escape_string($this->metatitle);
			$this->metakey = mysql_real_escape_string($this->metakey);
			$this->metadesc = mysql_real_escape_string($this->metadesc);
			$this->hidden = mysql_real_escape_string($this->hidden);
			$res_max = $conn->Execute("SELECT MAX(ordine) as maxordine FROM articoli_new WHERE lang='$this->lang' AND cid='$this->cid';");
			$maxordine = $res_max->Fields("maxordine");
			$maxordine++;
			$this->ordine = $maxordine;
			$res_max->Close();
		}
		//controllo la dimensione delle immagini
		if($himage_tmb == "")  {
		} else
		$my_image_tmb = $himage_tmb;
		if($himage_big == "" && $this->idarticolo == "") {
		 if($this->image_big["name"] != "")  {
		  $this->image_big["name"] = str_replace(" ","",$this->image_big["name"]);
		  $image_big = new Image($this->image_big["tmp_name"]);
		  $image_big->SaveProportionateImage($path_tmp.$this->image_big["name"],80,0,BIG_W);
		  $my_image_tmb = "tmb_".$this->image_big["name"];
		  $image_big->SaveProportionateImage($path_tmp.$my_image_tmb,80,0,TMB_W);
		  $my_image = "80_".$this->image_big["name"];
		  $image_big->SaveProportionateImage($path_tmp.$my_image,80,0,IMAGE_W);
		  $my_image_big = $this->image_big["name"];
		 }
		} else {
			$my_image = $himage;
			$my_image_big = $himage_big;
		}
		######################## VIDEO ######################################################
		if($this->idarticolo == "")  {
		 if($this->video["name"] != "")  {
		  $video = new Image($this->vide["tmp_name"]);
		  $error .= $video->CheckSizeFormat($this->video,VIDEO_W,VIDEO_H,"video");
		  $my_video = $video->name;
		 }
		} else
		$my_video = "";
		########################################################################################
		$this->desc = str_replace("\r","<br>",$this->desc);
		//inizio procedura di inserimento
		$qry = "INSERT INTO articoli_new VALUES(NULL,'$this->cid','$this->codice','$this->titolo1','$this->titolo2','$this->desc','$my_image_tmb','$my_image','$my_image_big','$this->prezzo1','$this->prezzo2','$this->spedizione','$this->spedizione2','$this->promozione','$this->vetrina','$this->novita','$this->minimo','y','$this->lang','$this->ordine','$this->peso','$my_video','$this->scheda','0','$this->disp','n', '$this->tagtitle','$this->tagkey','$this->tagdesc','$this->metatitle','$this->metakey','$this->metadesc','$this->hidden','$this->correlato1','$this->correlato2','$this->correlato3',0,'$this->fornitore','$this->costo','$this->giardino','$this->produttore',0);";
		//die($qry);
		$rs = $conn->Execute($qry);
		if ($rs) {
			$error1 = "Articolo inserito con successo.<br>";
			//creo la cartella dell'articolo
			$id = $conn->Insert_ID();
			$connect = ftp_connect($ftp_host);
		 $login = ftp_login($connect, $ftp_username, $ftp_pwd);
		 //if(mkdir($path_image.$id)) {
		 ftp_site($connect, "CHMOD 0777 ".$path_image_ftp);
		 if(ftp_mkdir($connect, $path_image_ftp.$id)) {
		 	//inserisco le immagini corrette
		 	ftp_site($connect, "CHMOD 0777 ".$path_image_ftp.$id);
		 	//se devo fare una copia
		 	if($this->idarticolo != "") {
		 		copy($path_image.$this->idarticolo."/".$this->image_tmb,$path_image.$id."/".$this->image_tmb);
		 		copy($path_image.$this->idarticolo."/".$this->image,$path_image.$id."/".$this->image);
		 		copy($path_image.$this->idarticolo."/".$this->image_big,$path_image.$id."/".$this->image_big);
		 	}
		 	// copio il tmb
		 	if(file_exists($path_tmp.$my_image_tmb) && $my_image_tmb != "") {
		 		if(copy($path_tmp.$my_image_tmb,$path_image.$id."/".$my_image_tmb))
		 		unlink($path_tmp.$my_image_tmb);
		 	}
		 	// copio l'immagine media
		 	if(file_exists($path_tmp.$my_image) && $my_image != "") {
		 		if(copy($path_tmp.$my_image,$path_image.$id."/".$my_image))
		 		unlink($path_tmp.$my_image);
		 	}
		 	// copio l'immagine big
		 	if(file_exists($path_tmp.$my_image_big) && $my_image_big != "") {
		 		if(copy($path_tmp.$my_image_big,$path_image.$id."/".$my_image_big))
		 		unlink($path_tmp.$my_image_big);
		 	}
		 	// copio il video
		 	if(file_exists($path_tmp.$this->video["name"]) && $this->video["name"] != "") {
		 		if(copy($path_tmp.$this->video["name"],$path_image.$id."/".$this->video["name"]))
		 		unlink($path_tmp.$this->video["name"]);
		 	}
		  //chmod($path_name.$id, 0775);
		  ftp_site($connect, "CHMOD 0755 ".$path_image_ftp.$id);
		  ftp_site($connect, "CHMOD 0755 ".$path_image_ftp);
		  ftp_quit($connect);
		 }
		 $rs->Close();
		 ## VARIANTI ##
		 foreach($varianti as $variante) {
		 	list($idattributo,$idvalore) = explode(":",$variante);
		 	if($idvalore>0) {
		 		$conn->Execute("INSERT INTO articolo_attributo VALUES($id,$idattributo,$idvalore);");
		 	}
		 }
		}
		else
		$error1 = "Errore nell'inserimento.<br>";
		return $error1.$error;
	}

	function update($cid,$codice,$titolo1,$titolo2,$desc,$image,$image_big,$prezzo1,$prezzo2,$spedizione,$spedizione2,$promozione,$vetrina,$novita,$minimo,$peso,$video,$scheda,$disp,$tagtitle, $tagkey, $tagdesc, $metatitle, $metakey, $metadesc, $hidden, $fornitore, $attributo,$costo,$produttore,$varianti)  {
		global $conn, $path_image, $path_tmp, $max_size_image, $ftp_host,$ftp_username, $ftp_pwd,$path_image_ftp;
		//controllo la dimensione delle immagini
		if($this->import=="1") {
			if($image_big["name"] != "")  {
				$obj = new Image($image_big["tmp_name"]);
				$image2 = $data[1].".jpg";
				$tmb = "tmb_".$image2;
				$big = "big_".$image2;
				$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$big, 100,0,200);
				$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$tmb, 100,0,40);
				$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$image2, 100,0,80);
			}
		} else {
			if($image_big["name"] != "")  {
				$image_big["name"] = str_replace(" ","",$image_big["name"]);
				$new_image_big = new Image($image_big["tmp_name"]);
		  		$new_image_big->SaveProportionateImage($path_tmp.$image_big["name"],80,0,BIG_W);
		  		$my_image_tmb = "tmb_".$image_big["name"];
		  		$new_image_big->SaveProportionateImage($path_tmp.$my_image_tmb,80,0,TMB_W);
		  		$my_image = "80_".$image_big["name"];
		  		$new_image_big->SaveProportionateImage($path_tmp.$my_image,80,0,IMAGE_W);
		  		$my_image_big = $image_big["name"];
				$qry_tmb = ", image_tmb='$my_image_tmb'";
				$qry_big = ", image_big='$my_image_big'";
				$qry_image = ", image='$my_image'";
			}
		}
		########################## VIDEO ########################################################
		if($video["name"] != "")  {
			$new_video = new Image($video["tmp_name"]);
			$error .= $new_video->CheckSizeFormat($video,VIDEO_W,VIDEO_H,"video");
			$qry_video = ", video='$new_video->name'";
		}
		########################################################################################
		$desc = str_replace("\r","<br>",$desc);
		$qry_order = "";
		if($cid!=$this->cid)  {
	  //devo aggiornare l'ordine nelle 2 categorie
			$res_max = $conn->Execute("SELECT MAX(ordine) as maxordine FROM articoli_new WHERE lang='$this->lang' AND cid='$cid';");
			$maxordine = $res_max->Fields("maxordine");
		 if(is_null($maxordine))
		 $newordine = 0;
		 else
		 $newordine = $maxordine + 1;
		 $res_max->Close();
		 $qry_order = ",ordine='$newordine'";
		}
		//inizio la procedura di update
		$qry = "UPDATE articoli_new SET cid='$cid', codice='$codice', titolo1='$titolo1', titolo2='$titolo2', descrizione='$desc' $qry_tmb $qry_image $qry_big $qry_video ,prezzo1='$prezzo1', prezzo2='$prezzo2', spedizione='$spedizione', spedizione2='$spedizione2', promozione='$promozione', vetrina='$vetrina', novita='$novita', minimo='$minimo',peso='$peso',scheda='$scheda',disp='$disp',tagtitle='$tagtitle', tagkey='$tagkey', tagdesc='$tagdesc', metatitle='$metatitle', metakey='$metakey',metadesc='$metadesc',hidden='$hidden',fornitore='$fornitore',costo=$costo,produttore='$produttore' $qry_order WHERE idarticolo='$this->idarticolo';";
		//die($qry);
		$rs = $conn->Execute($qry);
		if ($rs)  {
			$error1 = "Articolo aggiornato con successo!<br>";
			// Attributi ricerca
			$id = $this->idarticolo;
			$connect = ftp_connect($ftp_host);
			$login = ftp_login($connect, $ftp_username, $ftp_pwd);
			/*
			 if(!file_exists($_SERVER['DOCUMENT_ROOT']."/gestione/imgs_prodotti/".$id))
			 $folder = ftp_mkdir($connect, $path_image_ftp.$id);
			 */
			ftp_site($connect, "CHMOD 0777 ".$path_image_ftp);
			ftp_site($connect, "CHMOD 0777 ".$path_image_ftp.$id);
			if(file_exists($path_tmp.$my_image_tmb) && $my_image_tmb != "") {
				if(copy($path_tmp.$my_image_tmb,$path_image.$id."/".$my_image_tmb))
				unlink($path_tmp.$my_image_tmb);
				if(file_exists($path_image.$id."/".$this->image_tmb) && $this->image_tmb != $my_image_tmb && $this->image_tmb != "")
				unlink($path_image.$id."/".$this->image_tmb);
			}
			// copio l'immagine media
			if(file_exists($path_tmp.$my_image) && $my_image != "") {
				if(copy($path_tmp.$my_image,$path_image.$id."/".$my_image))
				unlink($path_tmp.$my_image);
				if(file_exists($path_image.$id."/".$this->image) && $this->image != $my_image && $this->image != "")
				unlink($path_image.$id."/".$this->image);
			}
			// copio l'immagine big
			if(file_exists($path_tmp.$my_image_big) && $my_image_big != "") {
				if(copy($path_tmp.$my_image_big,$path_image.$id."/".$my_image_big))
				unlink($path_tmp.$my_image_big);
				if(file_exists($path_image.$id."/".$this->image_big) && $this->image_big != $my_image_big && $this->image_big != "")
				unlink($path_image.$id."/".$this->image_big);
			}
			############################## VIDEO ################################################
			if(file_exists($path_tmp.$video["name"]) && $video["name"] != "") {
				if(copy($path_tmp.$video["name"],$path_image.$id."/".$video["name"]))
				unlink($path_tmp.$video["name"]);
				if(file_exists($path_image.$id."/".$this->video) && $this->video != $new_video->name && $this->video != "" && $this->lang == "ita")
				unlink($path_image.$id."/".$this->video);
			}
			#####################################################################################
			$rs->Close();
			ftp_site($connect, "CHMOD 0755 ".$path_image_ftp.$id);
			ftp_site($connect, "CHMOD 0755 ".$path_image_ftp);
			ftp_quit($connect);
			## VARIANTI ##
			$conn->Execute("DELETE FROM articolo_attributo WHERE idarticolo=$id;");
			foreach($varianti as $variante) {
		 	list($idattributo,$idvalore) = explode(":",$variante);
		 	if($idvalore>0) {
		 		$conn->Execute("INSERT INTO articolo_attributo VALUES($id,$idattributo,$idvalore);");
		 	}
		 	}
		}
		else
		$error1 = "Errore nell'operazione!";
		return $error1.$error;
	}

	function delete()   {
		global $conn, $path_image, $path_image_ftp, $path_tmp, $max_size_image, $ftp_host,$ftp_username, $ftp_pwd;
		//procedura di eliminazione
		$qry = "DELETE FROM articoli_new WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs)  {
	  $error = 0;
	  // cancello la directory delle immagini in ftp
	  $connect = ftp_connect($ftp_host);
		 $login = ftp_login($connect, $ftp_username, $ftp_pwd);
		 $files = ftp_nlist($connect, $path_image_ftp.$this->idarticolo);
		 if(is_array($files) && count($files) > 0)  {
		 	foreach($files as $chiave => $nome)  {
		 		@ftp_delete($connect, $nome);
		 	}
		 }
		 ftp_rmdir($connect, $path_image_ftp.$this->idarticolo);
		 ftp_quit($connect);
		 $rs->Close();
		 ## VARIANTI ##
		 $conn->Execute("DELETE FROM articolo_attributo WHERE idarticolo=$this->idarticolo;");
		}  else
		$error = "Errore nell'operazione.";
		return $error;
	}

	function up()  {
		global $conn;
		$ordineup = $this->ordine-1;
		$qryup = "UPDATE articoli_new SET ordine=ordine+1 WHERE ordine='$ordineup' AND lang='$this->lang' AND cid='$this->cid';";
		$rs = $conn->Execute($qryup);
		if ($rs) {
			$qry = "UPDATE articoli_new SET ordine=ordine-1 WHERE ordine='$this->ordine' AND lang='$this->lang' AND idarticolo='$this->idarticolo' AND cid='$this->cid';";
			$rs = $conn->Execute($qry);
			if($rs) {
				$error = "0";
			}  else  {
				$error = "Errore nell'operazione.";
			}
		}  else
		$error = "Errore nell'operazione.";
		$rs->Close();
		return $error;
	}

	function down()  {
		global $conn;
		$ordinedown = $this->ordine + 1;
		$qrydown = "UPDATE articoli_new SET ordine=ordine-1 WHERE ordine='$ordinedown' AND lang='$this->lang' AND cid='$this->cid';";
		$rs = $conn->Execute($qrydown);
		if ($rs) {
			$qry = "UPDATE articoli_new SET ordine=ordine+1 WHERE ordine='$this->ordine' AND lang='$this->lang' AND cid='$this->cid' AND idarticolo='$this->idarticolo';";
			$rs = $conn->Execute($qry);
			if($rs) {
				$error = "0";
			}  else  {
				$error = "Errore nell'operazione.";
			}
		}  else
		$error = "Errore nell'operazione.";
		$rs->Close();
		return $error;
	}

	function disactive()  {
		global $conn;
		$qry = "UPDATE articoli_new SET attivo='n' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function active()  {
		global $conn;
		$qry = "UPDATE articoli_new SET attivo='y' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function bannerIn()  {
		global $conn;
		$qry = "UPDATE articoli_new SET banner='y' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function bannerOut()  {
		global $conn;
		$qry = "UPDATE articoli_new SET banner='n' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function vetrinaIn()  {
		global $conn;
		$qry = "UPDATE articoli_new SET vetrina='y' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function vetrinaOut()  {
		global $conn;
		$qry = "UPDATE articoli_new SET vetrina='n' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}
	
	function vetrinaCatIn()  {
		global $conn;
		$qry = "UPDATE articoli_new SET vetrinacat=1 WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function vetrinaCatOut()  {
		global $conn;
		$qry = "UPDATE articoli_new SET vetrina=0 WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function novitaIn()  {
		global $conn;
		$qry = "UPDATE articoli_new SET novita='y' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function novitaOut()  {
		global $conn;
		$qry = "UPDATE articoli_new SET novita='n' WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
		return $error;
	}

	function addHit($n)  {
		global $conn;
		$qry = "UPDATE articoli_new SET hit=hit+$n WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
	}

	function updDisp($n)  {
		global $conn;
		$qry = "UPDATE articoli_new SET disp=disp-$n WHERE idarticolo='$this->idarticolo';";
		$rs = $conn->Execute($qry);
		if($rs) {
			$error = "0";
		}  else  {
			$error = "Errore nell'operazione.";
		}
		$rs->Close();
	}

	function getMenusx($lang,$class="")  {
		global $conn;
		if($class!="")
		$class = "class=$class";
		$menu = "";
		$qry = "SELECT cid,titolo FROM categorie WHERE lang='$lang' AND attivo='y' ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		if($rs)  {
	  while(list($cid,$titolo) = @array_values($rs->FetchRow()))  {
	  	$menu .= "<a $class href=\"webproduct.php?cid=$cid\">$titolo</a>";
	  }
	  $rs->Close();
		}
		return $menu;
	}

	function getNavbar($cid1,$cid2,$cid3="")  {
		global $conn;
		$cat1 = new category($cid1);
		$cat2 = new category($cid2);
		$cat3 = new category($cid3);
		switch($cid1) {
			case 2:
				//piscine
				$folder2 = "piscine";
				break;
					
			case 3:
				//giardino
				$folder2 = "giardino";
				break;
		}
		$search = Array(' ','/','"');
		if($cat1->titolo!="")
		$nav1 = "<a class=\"navbar\" href=\"/$folder2/\">$cat1->titolo</a> ";
		if($cat2->titolo!="")
		$nav2 = " :: <a class=navbar href=\"/".fromTitToUrl($cat2->hidden)."/\">$cat2->titolo</a>";
		if($cat3->titolo!="")
		$nav3 = " :: <a class=navbar href=\"/".fromTitToUrl($cat2->hidden)."/".fromTitToUrl($cat3->hidden)."/\">$cat3->titolo</a>";
		$navbar = " $nav1".$nav2.$nav3;
		return $navbar;
	}

	function getPercorso($cid,$result)  {
		global $conn;
		$newcid = new category($cid);
		if($newcid->idfather != "0" && $newcid->idfather != "")  {
			$father = new category($newcid->idfather);
			$result = $father->titolo." : $result";
			$result = articoli::getPercorso($newcid->idfather,$result);
		}
		return $result;
	}

	function getGallery() {
		$path = $_SERVER['DOCUMENT_ROOT']."/immagini-piscine/";
		if(file_exists($path.$this->codice."_1.jpg")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_1.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image1 = '<a href="/immagini-piscine/'.$this->codice.'_1.jpg"><img src="/immagini-piscine/'.$this->codice.'_1.jpg" width="'.$w.'" border="0"></a>';
		} elseif(file_exists($path.$this->codice."_1.JPG")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_1.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image1 = '<a href="/immagini-piscine/'.$this->codice.'_1.jpg"><img src="/immagini-piscine/'.$this->codice.'_1.JPG" width="'.$w.'" border="0"></a>';
		} if(file_exists($path.$this->codice."_2.jpg")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_2.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image2 = '<a href="/immagini-piscine/'.$this->codice.'_2.jpg"><img src="/immagini-piscine/'.$this->codice.'_2.jpg" width="'.$w.'" border="0"></a>';
		} elseif(file_exists($path.$this->codice."_2.JPG")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_2.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image2 = '<a href="/immagini-piscine/'.$this->codice.'_2.JPG"><img src="/immagini-piscine/'.$this->codice.'_2.JPG" width="'.$w.'" border="0"></a>';
		} if(file_exists($path.$this->codice."_3.jpg")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_3.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image3 = '<a href="/immagini-piscine/'.$this->codice.'_3.jpg"><img src="/immagini-piscine/'.$this->codice.'_3.jpg" width="'.$w.'" border="0"></a>';
		} elseif(file_exists($path.$this->codice."_3.JPG")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_3.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image3 = '<a href="/immagini-piscine/'.$this->codice.'_3.JPG"><img src="/immagini-piscine/'.$this->codice.'_3.JPG" width="'.$w.'" border="0"></a>';
		} if(file_exists($path.$this->codice."_4.jpg")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_4.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image4 = '<a href="/immagini-piscine/'.$this->codice.'_4.jpg"><img src="/immagini-piscine/'.$this->codice.'_4.jpg" width="'.$w.'" border="0"></a>';
		} elseif(file_exists($path.$this->codice."_4.JPG")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_4.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image4 = '<a href="/immagini-piscine/'.$this->codice.'_4.JPG"><img src="/immagini-piscine/'.$this->codice.'_4.JPG" width="'.$w.'" border="0"></a>';
		} if(file_exists($path.$this->codice."_5.jpg")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_5.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image5 = '<a href="/immagini-piscine/'.$this->codice.'_5.jpg"><img src="/immagini-piscine/'.$this->codice.'_5.jpg" width="'.$w.'" border="0"></a>';
		} elseif(file_exists($path.$this->codice."_5.JPG")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_5.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image5 = '<a href="/immagini-piscine/'.$this->codice.'_5.JPG"><img src="/immagini-piscine/'.$this->codice.'_5.JPG" width="'.$w.'" border="0"></a>';
		} if(file_exists($path.$this->codice."_6.jpg")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_6.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image6 = '<a href="/immagini-piscine/'.$this->codice.'_6.jpg"><img src="/immagini-piscine/'.$this->codice.'_6.jpg" width="'.$w.'" border="0"></a>';
		} elseif(file_exists($path.$this->codice."_6.JPG")) {
			list($width,$height, $type, $attr) = getimagesize($path.$this->codice."_6.jpg");
			$width > 100 ? $w=100 : $w=$width;
			$image6 = '<a href="/immagini-piscine/'.$this->codice.'_6.JPG"><img src="/immagini-piscine/'.$this->codice.'_6.JPG" width="'.$w.'" border="0"></a>';
		}
		$gallery = $image1.$image2.$image3.$image4.$image5.$image6;
		return $gallery;
	}

	function getDetail()  {
		global $conn,$image_rel;
		##################################### SELEZIONE ARTICOLO IMPORT ###################################
		switch($this->import) {
			case 0:
				if($this->image_big) {
		  			$image = "<img src=\"/gestione/imgs_prodotti/".$this->idarticolo."/".str_replace(" ","_",$this->image_big)."\" border=0>";
					$image_rel = "http://www.bsvillage.com/gestione/imgs_prodotti/".$this->idarticolo."/".str_replace(" ","_",$this->image_big);
				} else
		  $image = "&nbsp;";
		  $correlati = $this->getCorrelatiWeb();
		  break;

			case 1:
				if($this->image_big) {
		  			$image = "<img src=\"/immagini-piscine/".$this->image_big."\" border=0>";
		  			$image_rel = "http://www.bsvillage.com/immagini-piscine/".$this->image_big;
				}
		  else
		  $image = "&nbsp;";
		  $correlati = $this->getCorrelatiWebImport();
		  $gallery = '<div class="photogallery" id="gallery">'.$this->getGallery().'</div>';
		  break;
		}
		switch($this->lang)  {
	  case "ita":
	  	$prezzo1 = "Prezzo IVA inclusa";
	  	$prezzo2 = "Prezzo scontato";
		$prezzo12 = "Prezzo";
	  	$spedizione = "Spese di spedizione";
	  	$spedizione2 = "A partire dal secondo oggetto";
	  	$sped_text = "Gratuita";
	  	$disp = "Disponibilit&agrave;";
	  	$quantita = "Inserisci Quantit&agrave;";
	  	$nodisp = "Prodotto al momento Esaurito";
	  	$cart = "carrello.jpg";
	  	$altimage = "Metti nel carrello";
	  	break;
	  	 
	  case "eng":
	  	if($this->image_big)
		  $image = "<img src=\"../gestione/imgs_prodotti/".$this->idarticolo."/".$this->image_big."\" border=0>";
		  else
		  $image = "&nbsp;";
		  $prezzo1 = "Price";
		  $prezzo2 = "Our price";
		  $spedizione = "Shipping in EU";
		  $ask = "<br><a href=\"mailto:simone@bsvillage.com\" class=tit02>Ask Shipping Cost</a>";
		  $spedizione2 = "From the second item";
		  $sped_text = "Free";
		  $quantita = "Quantity";
		  $disp = "Availability";
		  $nodisp = "Coming Soon";
		  $cart = "but_carrello-eng.gif";
		  $altimage = "add to cart";
		  break;
		}
		list($listino,$scontato,$spedizionev) = articoli::getPrezzo($this->idarticolo,$this->cid,$this->prezzo1,$this->prezzo2,($this->spedizione > 0 && $this->spedizione != 9999 ? $this->spedizione : 10),$this->fornitore);
		if($this->spedizione == "0.00" || $spedizionev == 0)
		$sped_str = $sped_text;
		elseif($this->spedizione == 9999)
		$sped_str = '<a href="mailto:simone@bsvillage.com?subject=Richiesta Preventivo per '.$this->titolo1.'">Chiedi un preventivo</a>';
		else
		$sped_str = number_format($spedizionev,2,',','.')." &euro;";
		if($this->spedizione2 == "0.00")
		$sped_str2 = $sped_text;
		else
		$sped_str2 = number_format($this->spedizione2,2,',','.');
		if($this->promozione == "y" && $this->prezzo2 !="")
		  $prezzo = '<tr>
                    <td><img src="/images/spacer.gif" width="20" height="10"></td>
                                <td width="60" valign="top">
									<span class="testo_dett2"><b>'.$prezzo12.':</b>
								</td>
								<td align="left">
									<span class=prezzo_pieno2>'.number_format($listino,2,",",".").'</span> &euro;</span><br />
									<span class=prezzo_scont2>'.number_format($scontato,2,",",".").' &euro;</span>
								</td>
                              </tr>';
		else
		  $prezzo = '<tr>
                    <td><img src="/images/spacer.gif" width="20" height="10"></td>
                                <td><span class="testo_dett2"><b>'.$prezzo1.':</b> '.number_format($listino,2,",",".").' &euro;</span></td>
                              </tr>';
		########################### disponibilità ############################################
		switch($this->disp)  {
			case "-1":
				$strdisp = '<span style="color:red;"><b>Articolo al momento esaurito!</b></span>';
				break;

			case "0":
				$strdisp = '<span style="color:red;"><b>Disponibilit&agrave; dell\'articolo da verificare.</b></span>';
				break;

			case "1":
				$strdisp = '<span style="color:green;"><b>Articolo disponibile</b></span>';
				break;
		}
		############################# VIDEO ###################################################
		if($this->video!="" && substr($this->video,-3)=="flv")
		$video = '<tr>
                        <td class="plain"><img src="/images/spacer.gif" width="35" height="5"></td>
                      </tr>
                      <tr>
                       <td align=center valign=top>
                       <div id="container"></div>
					   <script type="text/javascript" src="/js/swfobject.js"></script>
	<script type="text/javascript">
		var s1 = new SWFObject("/video/mediaplayer.swf","mediaplayer","400","323","8");
		s1.addParam("allowfullscreen","true");
		s1.addVariable("width","400");
		s1.addVariable("height","323");
		s1.addVariable("file","/gestione/imgs_prodotti/'.$this->idarticolo.'/'.$this->video.'");
		s1.write("container");
	</script>
					   </td>
                      </tr>
					  <tr>
                        <td class="plain"><img src="/images/spacer.gif" width="35" height="5"></td>
                      </tr>';
		/*
		 if($correlati!="")
		 $height = 'height="300"';
		 else
		 $height = '';
		 */
		if($this->codice!="") $codice = '<strong>Cod. articolo:</strong> '.$this->codice.'';
		#######################################################################################
		$content = '<table width="100%" border="0" cellspacing="0" cellpadding="0">
    				<form name=formdettaglio action="/webproduct.php" method=POST>
                      <tr>
                        <td class="plain"><table width="98%" border="0" cellpadding="5" cellspacing="0">
                          <tr>
                            <td><div align="center" class="tit01"><h1>'.$this->titolo1.'</h1></div></td>
                          </tr>
                        </table></td>
                      </tr>
                      <tr>
                        <td class="plain"><img src="/images/spacer.gif" width="35" height="10"></td>
                      </tr>
                      <tr>
                        <td class="plain"><table width="688" border="0" cellspacing="0" cellpadding="0">
                          <tr>
                           <td width="10"><img src="/images/spacer.gif" width=10></td>
                            <td width="200" valign=top><table width="200" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                  <td valign=top align=right style="font-size:12px">'.$image.'</td>
                                </tr>
                                <tr>
                                  <td><img src="/images/spacer.gif" width="200" height="10"></td>
                                </tr>
                                './*<tr>
                                  <td>
									  <div align="left">
										<input type=hidden name=idarticolo value="'.$this->idarticolo.'">
										<input type=hidden name=op value=addtoCart>
										<a href="javascript:document.formdettaglio.submit();"><img alt="'.$altimage.'" src="/images/'.$cart.'" border=0></a>
										<p class="btnFBdett"><fb:like layout="button_count"></fb:like><p>
									  </div>
								  </td>
                                </tr>'*/'
                              </table>
							  </td>
                            <td width="800" valign=top><br><table width="100%" border="0" cellpadding="3" cellspacing="0">
							  '.$prezzo.'
                              <tr>
                                <td><img src="/images/spacer.gif" width="20" height="10"></td>
                                <td colspan="2"><span class="testo_dett"><b>'.$spedizione.':</b> '.$sped_str.' .'.$ask.'</span></td>
                              </tr>                              
                              <!--<tr>
                                <td><img src="/images/spacer.gif" width="20" height="10"></td>
                                <td colspan="2"><span class="testo_dett"><b>'.$spedizione2.':</b> '.$sped_str2.' &euro;.</span></td>
                              </tr>-->
							  <tr>
							  	<td><img src="/images/spacer.gif" width="20" height="10"></td>
							  	<td colspan="2"><span class="testo_dett">'.$codice.'</span></td>
							  </tr>
							  <tr>
                                <td><img src="/images/spacer.gif" width="20" height="10"></td>
                                <td colspan="2"><span class="testo_dett">'.$strdisp.'</td>
                              </tr>';
							  
				if ($this->disp!="-1") {
				$content .= ' <tr>
                                <td><img src="/images/spacer.gif" width="20" height="10" colspan="3"></td>
							  </tr>
							  <tr>
                                <td><img src="/images/spacer.gif" width="20" height="10"></td>
                                <td colspan="2"><span class="testo_dett"><b>'.$quantita.':</b> <input type=text name=quantity value="'.$this->minimo.'" size=5></span></td>
                              </tr>';
				}
				
				$content .= ' <tr>
							    <td></td>
							  	<td colspan="2">
								  <div align="left">
								  	';
									
			if ($this->disp=="-1") {
				$content .= '		<a href="#form"><img alt="'.$altimage.'" src="/images/btnPrev.jpg" border=0></a>';
			} else {
				$content .= '		<input type=hidden name=idarticolo value="'.$this->idarticolo.'">
									<input type=hidden name=op value=addtoCart>
									<a href="javascript:document.formdettaglio.submit();"><img alt="'.$altimage.'" src="/images/'.$cart.'" border=0></a>';
			}
			$content .= '			<p class="btnFBdett"><fb:like layout="button_count"></fb:like><p>
								  </div>
							  	</td>
							  </tr>
                            </table>
							</td>
                            <td width=200 valign=top rowspan="2">
								'.$correlati.'
							</td>
                          </tr>
                          <tr>
                          	<td><img src="/images/spacer.gif" width=10></td>
                            <td colspan="2" valign="top" '.$height.'>
								<span class="testo_dett"><b>Codice BUONO SCONTO:</b> <input type=text name=buono size=5></span><br>
								<p class="plain">Inserisci il codice poi clicca su <strong>Compra subito</strong>.</p>
								<p>&nbsp;</p>
								<p class="tit02">ORDINA VIA FAX: <a class="plain" href="../download/Modello_Ordine_Fax_bsvillage.PDF" target="_BLANK">scarica modulo PDF</a> - <a class="plain" href="../download/Modello_Ordine_Fax_bsvillage.doc" target="_BLANK">scarica modulo DOC</a></p>
								<p>&nbsp;</p>
								<p class="testo_dett sottotitolo"><b>'.$this->titolo2.'</b></p>
                            	<p>&nbsp;</p>
                            	<p class="testo_dett" style="font-size:12px;padding:5px;">'.$this->desc.'</p>
                            	<p>&nbsp;</p>
							</td>
                          </tr>
                        </table>
						</td>
                        </tr>
                      <tr>
                        <td class="plain"><img src="/images/spacer.gif" width="35" height="5"></td>
                      </tr>
                      '.$video.'
                      <tr>
                       <td class=plain>'.$this->scheda.'</td>
                      </tr>
                      <tr>
                       <td class=plain>&nbsp;</td>
                      </tr>
                      <tr>
                       <td class=plain>'.$gallery.'</td>
                      </tr>
                      </form>
                    </table>
					<table width="670" border="0" cellspacing="0" cellpadding="0" class="plain" align="center">
                        <tr>
                          <td><img src="http://www.bsvillage.com/images/boxProdTop.gif" width="670" height="18"></td>
                        </tr>
                        <tr>
                          <td background="http://www.bsvillage.com/images/boxProdCnt.gif"><table width="670" border="0" cellspacing="0" cellpadding="0" class="plain">
                            <tr>
                              <td width="20"><img src="http://www.bsvillage.com/images/spacer.gif" height="20" width="20"></td>
                              <td width="630" align="center" class="plain"><a name="form">
<form method="post" action="http://www.bsvillage.com/postDataAweber.php" onsubmit="validazioneForm(\'name\', \'from\', \'privacy\'); return returnVal;">
<input type="hidden" name="meta_web_form_id" value="501809169">
<input type="hidden" name="meta_split_id" value="">
<input type="hidden" name="unit" value="bsvillage">
<input type="hidden" name="redirect" value="http://www.bsvillage.com/piscine/thanks.html" id="redirect_abd31bb456ada4775f7d95d09d3dfbc1">
<input type="hidden" name="meta_redirect_onlist" value="">
<input type="hidden" name="meta_adtracking" value="">
<input type="hidden" name="meta_message" value="1">
<input type="hidden" name="meta_required" value="name,from">
<input type="hidden" name="meta_forward_vars" value="0">
<input type="hidden" name="url_prodotto" value="http://www.bsvillage.com'.$_SERVER['REQUEST_URI'].'">
<table>
<tr><td colspan=2 align="center" class="plain"><div>
<h3 class="tit">Richiesta Informazioni sul prodotto</h3>
<div>Grazie a questo modulo potrete contattarci per informazioni tecniche o commerciali. Faremo il possibile per dare una risposta ai Vostri dubbi. Il Nome e l\'Email sono obbligatorie. Consigliamo di inserire un recapito telefonico <br /><br />'./*'Grazie a questo modulo potrete contattare i tecnici o i commerciali di BSVillage. Faremo il possibile per dare una risposta ai Vostri dubbi. Il Nome e l\'Email sono obbligatorie.'.*/'</div></div></td></tr>
<tr><td class="plain">Nome:</td><td><input type="text" name="name" id="name" value="" size="20"></td></tr>
<tr><td class="plain">Email:</td><td><input type="text" name="from" id="from" value="" size="20"></td></tr>
<tr><td class="plain">Telefono:</td><td><input type="text" name="custom Telefono" id="telefono" value="" size="20"></td></tr>
<tr><td class="plain">Seleziona il tipo di informazione che stai cercando:</td><td><select name="custom Seleziona il tipo di informazione che stai cercando">
<option value="Dettagli sul funzionamento">Dettagli sul funzionamento</option>
<option value="Compatibilita con altri prodotti">Compatibilit&agrave; con altri prodotti</option>
<option value="Ulteriori caratteristiche">Ulteriori caratteristiche</option>
<option value="Accessori del prodotto">Accessori del prodotto</option>
<option value="Pezzi di ricambio">Pezzi di ricambio</option>
<option value="Preventivo personalizzato">Preventivo personalizzato</option>
<option value="Altre informazioni">Altre informazioni</option>
</select></td></tr>
<tr><td valign="top" class="plain">Scrivi sinteticamente la tua richiesta di informazioni:</td><td><textarea name="custom Spiegaci sinteticamente che cosa vuoi sapere del prodotto" rows="6" cols="35"></textarea></td></tr>
<tr><td class="plain">Come mai hai deciso di contattarci?</td><td><select name="custom Come mai hai deciso di contattarci">
<option value="Per ricevere ulteriori informazioni prima dell\'acquisto">Per ricevere ulteriori informazioni prima dell\'acquisto</option>
<option value="I dettagli del prodotto non sono chiari">I dettagli del prodotto non sono chiari</option>
<option value="La scheda tecnica &egrave; mancante o incompleta">La scheda tecnica &egrave; mancante o incompleta</option>
<option value="Altri motivi">Altri motivi</option>
</select></td></tr>
   <tr><td></td>
   <td class="plain">
   <div>
		<p style="margin:10px 0">
		<input type="checkbox" value="yes" id="privacy" class="checkbox" name="custom Privacy" tabindex="616" />
		<label class="choice" for="privacy">Accetto l\'informativa sulla <a onclick="wopen(\'http://www.bsvillage.com/webpage.php?idpage=33&popup\', \'popup\', 850, 550); return false;" target="popup" href="http://www.bsvillage.com/webpage.php?idpage=33">Privacy</a></label>
		</p>
   </div>
</td></tr>
<tr><td align="center" colspan="2" style="text-align:center;"><input type="submit" name="submit" value="Invia la Tua Richiesta!"></td></tr>
</table>
</form>

<img src="http://forms.aweber.com/form/displays.htm?id=rAyMHAycjGyc" border="0" />
</td>
                              <td width="20"><img src="http://www.bsvillage.com/images/spacer.gif" height="20" width="20"></td>
                            </tr>
                          </table></td>
                        </tr>
                        <tr>
                          <td><img src="http://www.bsvillage.com/images/boxProdBtm.gif" width="670" height="18"></td>
                        </tr>
                      </table>
                        <table width="670" border="0" cellspacing="0" cellpadding="0">
                          <tr>
                            <td><img src="http://www.bsvillage.com/images/spacer.gif" width="670" height="10"></td>
                          </tr>
                        </table>';
		return $content;
	}

	function getVetrina($lang,$cid)  {
		global $conn;
		switch($lang)  {
	  case "ita":
	   $prezzo1 = "Prezzo IVA incl.";
	   $prezzo2 = "Scontato";
	   $compralo1 = "../images/compralo.gif";
	   break;
	    
	  case "eng":
	   $prezzo1 = "Price";
	   $prezzo2 = "Our price";
	   $compralo1 = "../images-eng/compralo.gif";
	   break;
		}
		$list_cid = category::getChild($cid,$cid);
		//die($list_cid);
		$qry = "SELECT idarticolo FROM articoli_new INNER JOIN categorie ON articoli_new.cid=categorie.cid WHERE articoli_new.lang='$lang' AND vetrina='y' AND articoli_new.attivo='y' AND (categorie.cid IN ($list_cid)) ORDER BY rand() LIMIT 0,9;";
		//die($qry);
		$content = '<table width="588" border="0" cellspacing="0" cellpadding="0">
					<tr>';
		$rs = $conn->Execute($qry);
		if($rs)  {
			$image_tmb = array();
			$prezzo = array();
			$prezzosc = array();
			$titolo = array();
			$compralo = array();
			$i = 0;
			while(!$rs->EOF)  {
				$articolo = new articoli($rs->Fields("idarticolo"));
				$cat = new category($articolo->cid);
				list($cid3,$cid2,$cid1) = explode("-",category::getParent($cat->cid,$cat->cid));
				if($cid1 == "")  {
			  $cid1 = $cid2;
			  $cid2 = $cid3;
			  $cid3 = "";
				}
				if($articolo->import==1)
				$folder = "/immagini-piscine";
				else
				$folder = "/gestione/imgs_prodotti/$articolo->idarticolo";
				if($articolo->image!="")
				$image_tmb[$i] = "<a href=\"webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cod3&idarticolo=$articolo->idarticolo\"><img width=80 src=\"$folder/".str_replace(" ","_",$articolo->image)."\" border=0 alt=\"Apri dettaglio\"></a>";
				else
				$image_tmb[$i] = "&nbsp;";
				if($articolo->prezzo2 != "0" && $articolo->promozione == "y") {
			  $prezzo[$i] = $prezzo1.': <span class="prezzo_pieno">'.number_format($articolo->prezzo1,2,",",".").'</span> &euro;';
			  $compralo[$i] = "<a href=\"webproduct.php?idarticolo=$articolo->idarticolo&cid1=$cid1&cid2=$cid2&cid3=$cod3\"><img src=\"".$compralo1."\" border=0></a>";
			  $prezzosc[$i] = $prezzo2.': '.number_format($articolo->prezzo2,2,",",".").' &euro;';
				}	else  {
			  $prezzo[$i] = $prezzo1.': '.number_format($articolo->prezzo1,2,',','.').' &euro;';
			  $prezzosc[$i] = "&nbsp;";
			  $compralo[$i] = "&nbsp;";
				}
				$titolo[$i] = '<a class=plain href="webproduct.php?cid1='.$cid1.'&cid2='.$cid2.'&cid3='.$cid3.'&idarticolo='.$articolo->idarticolo.'">'.$articolo->titolo1.'</a>';
				$i++;
				$rs->MoveNext();
			}
			$rs->Close();
		}
		$tmpl_file = "../gestione/templatesphp/vetrina.html";
		$thefile = implode("", file($tmpl_file));
		$thefile = addslashes($thefile);
		$thefile = "\$r_file=\"".$thefile."\";";
		eval($thefile);
		$content = $r_file;
		return $content;
	}

	function getPromozione($lang)  {
		switch($lang)  {
			case "ita":
				$prezzo1 = "Prezzo";
				$prezzo2 = "Business Shop";
		  break;

			case "eng":
				$prezzo1 = "Price";
				$prezzo2 = "Our price";
		  break;
		}
		global $conn;
		$qry = "SELECT idarticolo FROM articoli_new WHERE lang='$lang' AND promozione='y' AND attivo='y' AND prezzo2 <> '0' ORDER BY rand() LIMIT 0,4;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount() > 0)  {
			$image_tmb = array();
			$prezzo = array();
			$prezzosc = array();
			$titolo = array();
			$i = 0;
		 while(!$rs->EOF) {
		 	$articolo = new articoli($rs->Fields("idarticolo"));
		 	$cat = new category($articolo->cid);
		 	list($cid3,$cid2,$cid1) = explode("-",category::getParent($cat->cid,$cat->cid));
		 	if($cid1 == "")  {
		 		$cid1 = $cid2;
		 		$cid2 = $cid3;
		 		$cid3 = "";
		 	}
		 	if($articolo->import==1)
		 	$folder = "/immagini-piscine";
		 	else
		 	$folder = "/gestione/imgs_prodotti/$articolo->idarticolo";
		 	if($articolo->image_tmb!="")
		 	$image_tmb[$i] = "<a href=\"webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cid3&idarticolo=$articolo->idarticolo\"><img width=40 src=\"$folder/".str_replace(" ","_",$articolo->image_tmb)."\" border=0 alt=\"Apri dettaglio\"></a>";
		 	else
		 	$image_tmb[$i] = "&nbsp;";
		 	if($articolo->prezzo2 != "0" && $articolo->promozione == "y") {
			  $prezzo[$i] = $prezzo1.': <span class="prezzo_pieno">'.number_format($articolo->prezzo1,2,",",".").'</span> &euro;';
			  $prezzosc[$i] = $prezzo2.': '.number_format($articolo->prezzo2,2,",",".").' &euro;';
		 	}	else  {
			  $prezzo[$i] = $prezzo1.': '.number_format($articolo->prezzo1,2,',','.').' &euro;';
			  $prezzosc[$i] = "&nbsp;";
		 	}
		 	$titolo[$i] = '<a class=plain href="webproduct.php?cid1='.$cid1.'&cid2='.$cid2.'&cid3='.$cid3.'&idarticolo='.$articolo->idarticolo.'">'.$articolo->titolo1.'</a>';
		 	$i++;
		  $rs->MoveNext();
		 }
		}
		$rs->Close();
		$tmpl_file = "../gestione/templatesphp/promozione.html";
		$thefile = implode("", file($tmpl_file));
		$thefile = addslashes($thefile);
		$thefile = "\$r_file=\"".$thefile."\";";
		eval($thefile);
		$content = $r_file;
		return $content;
	}

	function getNovita($cid,$lang)  {
		global $conn;
		switch($lang)  {
			case "ita":
				$prezzo1 = "Prezzo";
				$prezzo2 = "sconto";
		  break;

			case "eng":
				$prezzo1 = "Price";
				$prezzo2 = "Our price";
		  break;
		}
		$elenco = category::getChild($cid,0);
		$qry = "SELECT idarticolo FROM articoli_new WHERE lang='$lang' AND novita='y' AND attivo='y' AND cid in ($elenco) ORDER BY rand() LIMIT 0,5;";
		$content = '';
		$rs = $conn->Execute($qry);
		if($rs->RecordCount() > 0)  {
			$image_tmb = array();
			$prezzo = array();
			$prezzosc = array();
			$titolo = array();
			$i = 0;
		 while(!$rs->EOF) {
		 	$articolo = new articoli($rs->Fields("idarticolo"));
		 	$cat = new category($articolo->cid);
		 	list($cid3,$cid2,$cid1) = explode("-",category::getParent($cat->cid,$cat->cid));
		 	if($cid1 == "")  {
		 		$cid1 = $cid2;
		 		$cid2 = $cid3;
		 		$cid3 = "";
		 	}
		 	if($articolo->import==1)
		 	$folder = "/immagini-piscine";
		 	else
		 	$folder = "/gestione/imgs_prodotti/$articolo->idarticolo";
		 	if($articolo->image_tmb!="")
		 	$image_tmb[$i] = "<a href=\"webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cid3&idarticolo=$articolo->idarticolo\"><img width=40 src=\"$folder/".str_replace(" ","_",$articolo->image_tmb)."\" border=0 alt=\"Apri dettaglio\"></a>";
		 	else
		 	$image_tmb[$i] = "&nbsp;";
		 	if($articolo->prezzo2 != "0" && $articolo->promozione == "y") {
			  $prezzo[$i] = $prezzo1.': <span class="prezzo_pieno">'.number_format($articolo->prezzo1,2,",",".").'</span> &euro;';
			  $prezzosc[$i] = $prezzo2.': '.number_format($articolo->prezzo2,2,",",".").' &euro;';
		 	}	else  {
			  $prezzo[$i] = $prezzo1.': '.number_format($articolo->prezzo1,2,',','.').' &euro;';
			  $prezzosc[$i] = "&nbsp;";
		 	}
		 	$titolo[$i] = '<a class=plain href="webproduct.php?cid1='.$cid1.'&cid2='.$cid2.'&cid3='.$cid3.'&idarticolo='.$articolo->idarticolo.'">'.$articolo->titolo1.'</a>';
		 	$i++;
		  $rs->MoveNext();
		 }
		}
		$rs->Close();
		$tmpl_file = "../gestione/templatesphp/novita.html";
		$thefile = implode("", file($tmpl_file));
		$thefile = addslashes($thefile);
		$thefile = "\$r_file=\"".$thefile."\";";
		eval($thefile);
		$content = $r_file;
		return $content;
	}

	function getNovitaHome($cid,$lang)  {
		global $conn;
		switch($lang)  {
			case "ita":
				$prezzo1 = "Prezzo";
				$prezzo2 = "sconto";
		  break;

			case "eng":
				$prezzo1 = "Price";
				$prezzo2 = "Our price";
		  break;
		}
		$elenco = category::getChild($cid,0);
		$qry = "SELECT idarticolo,cid,titolo1,image,promozione,vetrina,import,prezzo1,prezzo2,hidden,fornitore FROM articoli_new WHERE lang='$lang' AND novita='y' AND attivo='y' AND cid in ($elenco) ORDER BY rand() LIMIT 0,8;";
		$content = '';
		$rs = $conn->Execute($qry);
		if($rs->RecordCount() > 0)  {
			$image_tmb = array();
			$prezzo = array();
			$prezzosc = array();
			$titolo = array();
			$i = 1;
		 while(!$rs->EOF) {
		 	//$articolo = new articoli($rs->Fields("idarticolo"));
		 	$cat = new category($rs->Fields("cid"));
		 	$permalink = fromTitToUrl($rs->Fields("hidden"));
		 	if($rs->Fields("import")==1)
		 	$folder = "/immagini-piscine";
		 	else
		 	$folder = "/gestione/imgs_prodotti/".$rs->Fields("idarticolo");
		 	if($rs->Fields("image")!="")
		 	$image_tmb = "<a href=\"/$permalink/".$rs->Fields("idarticolo")."\" title=\"".$rs->Fields("titolo1")."\"><img alt=\"".$rs->Fields("titolo1")."\" width=80 src=\"$folder/".str_replace(" ","_",$rs->Fields("image"))."\" border=0 alt=\"Apri dettaglio\"></a>";
		 	else
		 	$image_tmb = "&nbsp;";
		 	list($listino,$scontato,$spedizione) = articoli::getPrezzo($rs->Fields("idarticolo"),$rs->Fields("cid"),$rs->Fields("prezzo1"),$rs->Fields("prezzo2"),10,$rs->Fields("fornitore"));
		 	if($rs->Fields("prezzo2") != "0" && $rs->Fields("promozione") == "y") {
			  $prezzo = $prezzo1.': <span class="prezzo_pieno">'.number_format($listino,2,",",".").'</span> &euro;';
			  $prezzosc = $prezzo2.': '.number_format($scontato,2,",",".").' &euro;';
		 	}	else  {
			  $prezzo = $prezzo1.': '.number_format($listino,2,',','.').' &euro;';
			  $prezzosc = "&nbsp;";
		 	}
		 	$titolo = '<a class=plain href="/'.$permalink.'/'.$rs->Fields("idarticolo").'">'.$rs->Fields("titolo1").'</a>';
		 	$i==2 || $i==5 ? $style='style="border-left:1px solid #e1e1e1;border-right:1px solid #e1e1e1;"' : $style="";
		 	$content .= '<div class="box-vetrina" '.$style.'>
		 					<div>'.$image_tmb.'</div>
		 					<div style="text-align:center">'.$titolo.'</div>
		 					<div style="text-align:center">
		 					<span class="prezzo_pieno">'.$prezzo.'</span><br>
		 					<span class="prezzo_scont">'.$prezzosc.'</span>
		 					</div>
		 	</div>';
		 	$i++;
		  $rs->MoveNext();
		 }
		}
		$rs->Close();
		return $content;
	}

	function getPath($cid,$path="")  {
		global $conn;
		$newCat = new category($cid);
		if($path != "")
		$path .= "-".$newCat->cid;
		else
		$path = $newCat->cid;
		if($newCat->idfather != "0")  {
			$path = articoli::getPath($newCat->idfather,$path);
		}
		return $path;
	}

	function getBanner($lang)  {
		global $conn,$_CONFIG,$cid;
		switch($lang)  {
			case "ita":
				$titbanner = $_CONFIG['titledx'];
				break;

			case "eng":
		  $titbanner = $_CONFIG['titledx_eng'];
		  break;
		}
		$elenco = category::getChild($cid,0);
		$qry = "SELECT idarticolo FROM articoli_new WHERE lang='$lang' AND attivo='y' AND banner='y' AND cid IN ($elenco) ORDER BY rand() LIMIT 0,10;";
		$rs = $conn->Execute($qry);
		$content = Array();
		if($rs->RecordCount() > 0)  {
			$banner = '<div id="slide">';
			$onload = 'flvFLSS1(\'slide\',3500,1,1,\'\',';
			$i = 0;
			while(!$rs->EOF)  {
		  $newArt = new articoli($rs->Fields("idarticolo"));
		  list($cid3,$cid2,$cid1) = explode("-",category::getParent($newArt->cid,$newArt->cid));
		  if($cid1 == "")  {
		  	$cid1 = $cid2;
		  	$cid2 = $cid3;
		  	$cid3 = "";
				}
		  if($newArt->import==1)
		  $folder = "/immagini-piscine";
		  else
		  $folder = "/gestione/imgs_prodotti/$newArt->idarticolo";
		  $permalink = fromTitToUrl($newArt->hidden);
		  if($i == "0")  {
		  	$first = '<img src="'.$folder.'/'.str_replace(" ","_",$newArt->image).'" border=0>';
		  	$onload .= '\''.$folder.'/'.str_replace(" ","_",$newArt->image).'\',\'/'.$permalink.'/'.$newArt->idarticolo.'\',\'\'';
		  } else
		  $onload .= ',\''.$folder.'/'.str_replace(" ","_",$newArt->image).'\',\'/'.$permalink.'/'.$newArt->idarticolo.'\',\'\'';
		  $rs->MoveNext();
		  $i++;
			}
			$onload .= ')';
			$banner .= $first.'</div>';
			$content[0] = '<table width="190" bgcolor="#FFFFFF">
					 <tr>
					   <td width="190" class="tit02" align=center style="text-align:center">'.$titbanner.'</td>
					 </tr>
					 <tr>
					   <td align=center valign=top style="text-align:center">'.$banner.'</td>
					 </tr>
					</table>';
			$content[1] = $onload;
		}
		return $content;
	}

	function getCorrelatiWeb()  {
		global $conn,$lang;
		switch($lang)  {
			case "ita":
				//$prezzo1 = "Prezzo IVA inc. :";
				//$prezzo2 = "Scontato:";
				$compralo1 = "/images/compralo-small.gif";
		  break;

			case "eng":
				$prezzo1 = "Price";
				$prezzo2 = "Our price";
				$compralo1 = "../images-eng/compralo.gif";
		  break;
		}
		$qry = "SELECT articoli_new.idarticolo as idarticolo FROM articoli_new INNER JOIN articoli_correlati ON articoli_new.idarticolo=articoli_correlati.idarticolo2 WHERE articoli_correlati.idarticolo1=$this->idarticolo ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			//stampo gli articoli
			$content .= '<table width=100% class=plain cellpadding=0 bgcolor=#D8D8D8>
		  				<tr>
		  					<td width=100% class="tit02">Ti suggeriamo anche...</td>
			  			 </tr>
						   <tr>
		  					<td>&nbsp;&nbsp;<input type="checkbox" id="allcorrelati" onClick="check_uncheck()"> Seleziona tutto per aggiungere questi articoli al carrello</td>
			  			 </tr>';
			while(!$rs->EOF)  {
				$articolo = new articoli($rs->Fields("idarticolo"));
				$permalink = fromTitToUrl($articolo->hidden);
				if($articolo->import==1)
				$folder = "/immagini-piscine";
				else
				$folder = "/gestione/imgs_prodotti/$articolo->idarticolo";
				if($articolo->image!="")
				$image_tmb = "<a class=plain href=\"/$permalink/".$articolo->idarticolo."\"><img width=80 src=\"$folder/".str_replace(" ","_",$articolo->image)."\" border=0 alt=\"Apri dettaglio\"></a>";
				else
				$image_tmb = "&nbsp;";
				list($listino,$scontato,$spedizionev) = articoli::getPrezzo($articolo->idarticolo,$articolo->cid,$articolo->prezzo1,$articolo->prezzo2,10,$articolo->fornitore);
				if($articolo->prezzo2 != "0" && $articolo->promozione == "y") {
			  $prezzo = $prezzo1.'<span class="prezzo_pieno">'.number_format($listino,2,",",".").'</span> &euro;';
			  $compralo = "&nbsp;&nbsp;<a href=\"/$permalink/".$articolo->idarticolo."\"><img src=\"".$compralo1."\" border=0></a>";
			  $prezzosc = '<br><span class="prezzo_scont">'.$prezzo2.''.number_format($scontato,2,",",".").' &euro;</span>';
				}	else  {
			  $prezzo = $prezzo1.''.number_format($listino,2,',','.').' &euro;';
			  $prezzosc = "&nbsp;";
			  $compralo = "&nbsp;";
				}
				$content .= "<tr><td><table width=100% class=plain cellpadding=2><tr><td><input type=\"checkbox\" name=\"correlati[]\" value=\"$articolo->idarticolo\"></td><td width=80>$image_tmb</td><td><a class=plain href=\"/$permalink/".$articolo->idarticolo."\">$articolo->titolo1</a><br>
				$prezzo
				$prezzosc
				$compralo
			</td></tr></table></td></tr>";
		  $rs->MoveNext();
			}
			$content .= "</table>";
		} else {
			$content = "";
		}
		return $content;
	}

	function getCorrelatiWebImport()  {
		global $conn,$lang;
		switch($lang)  {
			case "ita":
				//$prezzo1 = "Prezzo IVA inc. :";
				//$prezzo2 = "Scontato:";
				$compralo1 = "/images/compralo-small.gif";
		  break;

			case "eng":
				$prezzo1 = "Price";
				$prezzo2 = "Our price";
				$compralo1 = "../images-eng/compralo.gif";
		  break;
		}
		$content .= '<table width=100% class=plain cellpadding=0 bgcolor=#D8D8D8>
		  				<tr>
		  					<td width=100% class="tit02">Ti suggeriamo anche...</td>
			  			 </tr>
						   <tr>
		  					<td>&nbsp;&nbsp;<input type="checkbox" id="allcorrelati" onClick="check_uncheck()"> Seleziona tutto per aggiungere questi articoli al carrello</td>
			  			 </tr>';
		$qry = "SELECT DISTINCT idarticolo FROM articoli_new WHERE (codice='$this->correlato1' AND codice!='') OR (codice='$this->correlato2' AND codice!='') OR (codice='$this->correlato3' AND codice!='') ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			//stampo gli articoli
			while(!$rs->EOF)  {
				$articolo = new articoli($rs->Fields("idarticolo"));
				$permalink = fromTitToUrl($articolo->hidden);
				if($articolo->import==1)
				$folder = "/immagini-piscine";
				else
				$folder = "/gestione/imgs_prodotti/$articolo->idarticolo";
				if($articolo->image!="")
				$image_tmb = "<a class=plain href=\"/$permalink/".$articolo->idarticolo."\"><img width=80 src=\"$folder/".str_replace(" ","_",$articolo->image)."\" border=0 alt=\"Apri dettaglio\"></a>";
				else
				$image_tmb = "&nbsp;";
				if($articolo->prezzo2 != "0" && $articolo->promozione == "y") {
			  $prezzo = $prezzo1.'<span class="prezzo_pieno">'.number_format($articolo->prezzo1,2,",",".").'</span> &euro;';
			  $compralo = "&nbsp;&nbsp;<a href=\"/$permalink/".$articolo->idarticolo."\"><img src=\"".$compralo1."\" border=0></a>";
			  $prezzosc = '<br><span class="prezzo_scont">'.$prezzo2.''.number_format($articolo->prezzo2,2,",",".").' &euro;</span>';
				}	else  {
			  $prezzo = $prezzo1.''.number_format($articolo->prezzo1,2,',','.').' &euro;';
			  $prezzosc = "&nbsp;";
			  $compralo = "&nbsp;";
				}
				$content .= "<tr><td><table width=100% class=plain cellpadding=2><tr><td><input type=\"checkbox\" name=\"correlati[]\" value=\"$articolo->idarticolo\"></td><td width=80>$image_tmb</td><td><a class=plain href=\"/$permalink/".$articolo->idarticolo."\">$articolo->titolo1</a><br>
				$prezzo
				$prezzosc
				$compralo
			</td></tr></table></td></tr>";
		  $rs->MoveNext();
			}
		}
		############################# ALTRI CORRELATI ####################################################
		$qry = "SELECT articoli_new.idarticolo as idarticolo FROM articoli_new INNER JOIN articoli_correlati ON articoli_new.idarticolo=articoli_correlati.idarticolo2 WHERE articoli_correlati.idarticolo1=$this->idarticolo ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			//stampo gli articoli
			while(!$rs->EOF)  {
				$articolo = new articoli($rs->Fields("idarticolo"));
				$cat = new category($articolo->cid);
				list($cid3,$cid2,$cid1) = explode("-",category::getParent($cat->cid,$cat->cid));
				if($cid1 == "")  {
			  $cid1 = $cid2;
			  $cid2 = $cid3;
			  $cid3 = "";
				}
				if($articolo->import==1)
				$folder = "/immagini-piscine";
				else
				$folder = "/gestione/imgs_prodotti/$articolo->idarticolo";
				if($articolo->image!="")
				$image_tmb = "<a class=plain href=\"/$permalink/".$articolo->idarticolo."\"><img width=80 src=\"$folder/".str_replace(" ","_",$articolo->image)."\" border=0 alt=\"Apri dettaglio\"></a>";
				else
				$image_tmb = "&nbsp;";
				if($articolo->prezzo2 != "0" && $articolo->promozione == "y") {
			  $prezzo = $prezzo1.'<span class="prezzo_pieno">'.number_format($articolo->prezzo1,2,",",".").'</span> &euro;';
			  $compralo = "&nbsp;&nbsp;<a href=\"/$permalink/".$articolo->idarticolo."\"><img src=\"".$compralo1."\" border=0></a>";
			  $prezzosc = '<br><span class="prezzo_scont">'.$prezzo2.''.number_format($articolo->prezzo2,2,",",".").' &euro;</span>';
				}	else  {
			  $prezzo = $prezzo1.''.number_format($articolo->prezzo1,2,',','.').' &euro;';
			  $prezzosc = "&nbsp;";
			  $compralo = "&nbsp;";
				}
				$content .= "<tr><td><table width=100% class=plain cellpadding=2><tr><td><input type=\"checkbox\" name=\"correlati[]\" value=\"$articolo->idarticolo\"></td><td width=80>$image_tmb</td><td><a class=plain href=\"/$permalink/".$articolo->idarticolo."\">$articolo->titolo1</a><br>
				$prezzo
				$prezzosc
				$compralo
			</td></tr></table></td></tr>";
		  $rs->MoveNext();
			}

		}
		$content .= "</table>";
		return $content;
	}

	function getCorrelati()  {
		global $conn;
		if($this->import=="1") {
			$qry = "SELECT idarticolo,titolo1 as titolo,codice FROM articoli_new WHERE codice!='' AND (codice='$this->correlato1' OR codice='$this->correlato2' OR codice='$this->correlato3') ORDER BY titolo1;";
			$rs = $conn->Execute($qry);
			if($rs->RecordCount()>0)  {
				$result = '<table class=content width=500 cellpadding=2>';
				while(!$rs->EOF)  {
					$result .= '<tr>
			  					<td width="400"><b>'.$rs->Fields("titolo").'</b></td>
			  					<td align=center><a href="product_new.php?op=del_correlati_import&idarticolo='.$this->idarticolo.'&codice='.$rs->Fields("codice").'" onClick="return confirm(\'Sei sicuro di voler eliminare questo articolo correlato? Procedere?\');"><img src="imgs/ico_delete.gif" border=0 alt="Elimina"></a></td>
				  			</tr>';
					$rs->MoveNext();
				}
				$result .= '</table>';
			}
		}
		$qry = "SELECT articoli_new.idarticolo as idarticolo,articoli_new.titolo1 as titolo FROM articoli_new INNER JOIN articoli_correlati ON articoli_new.idarticolo=articoli_correlati.idarticolo2 WHERE articoli_correlati.idarticolo1=$this->idarticolo ORDER BY articoli_new.titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$result .= '<table class=content width=500 cellpadding=2>';
			while(!$rs->EOF)  {
				$result .= '<tr>
		  					<td width="400"><b>'.$rs->Fields("titolo").'</b></td>
		  					<td align=center><a href="product_new.php?op=del_correlati&idarticolo1='.$this->idarticolo.'&idarticolo2='.$rs->Fields("idarticolo").'" onClick="return confirm(\'Sei sicuro di voler eliminare questo articolo correlato? Procedere?\');"><img src="imgs/ico_delete.gif" border=0 alt="Elimina"></a></td>
			  			</tr>';
				$rs->MoveNext();
			}
			$result .= '</table>';
		}
		return $result;
	}
	
	function isCorrelato() {
		global $conn;
		$result = 0;
		$qry = "SELECT DISTINCT c.idfather as cid FROM categorie_correlate ca left join categorie c on 
		ca.cid=c.cid WHERE ca.idarticolo=$this->idarticolo;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$result = $rs->Fields("cid");
		}
		return $result;
	}

	function addCorrelati($idarticolo1,$idarticolo2)  {
		global $conn;
		$qry = "INSERT INTO articoli_correlati VALUES($idarticolo1,$idarticolo2);";
		$rs = $conn->Execute($qry);
		if($rs)
		$rs->Close();
	}

	function delCorrelati($idarticolo1,$idarticolo2)  {
		global $conn;
		$qry = "DELETE FROM articoli_correlati WHERE idarticolo1=$idarticolo1 AND idarticolo2=$idarticolo2;";
		$rs = $conn->Execute($qry);
		if($rs)
		$rs->Close();
	}

	function delCorrelatiImport($codice)  {
		global $conn;
		switch(true) {
			case $this->correlato1 == $codice:
				$campo = "correlato1";
				break;
					
			case $this->correlato2 == $codice:
				$campo = "correlato2";
				break;
					
			case $this->correlato3 == $codice:
				$campo = "correlato3";
				break;
		}
		$qry = "UPDATE articoli_new SET $campo='' WHERE idarticolo=$this->idarticolo;";
		$rs = $conn->Execute($qry);
		if($rs)
		$rs->Close();
	}

	function getCategorie()  {
		global $conn;
		$qry = "SELECT DISTINCT categorie.cid as cid,categorie.titolo as titolo FROM categorie_correlate INNER JOIN categorie ON categorie_correlate.cid=categorie.cid WHERE categorie_correlate.idarticolo=$this->idarticolo";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$result = '<table class=content width=500 cellpadding=2>';
			while(!$rs->EOF)  {
				$result .= '<tr>
		  					<td width="400"><b>'.$rs->Fields("titolo").'</b></td>
		  					<td align=center><a href="product_new.php?op=del_categoria&idarticolo='.$this->idarticolo.'&cid='.$rs->Fields("cid").'" onClick="return confirm(\'Sei sicuro di voler eliminare questa categoria correlata? Procedere?\');"><img src="imgs/ico_delete.gif" border=0 alt="Elimina"></a></td>
			  			</tr>';
				$rs->MoveNext();
			}
			$result .= '</table>';
		} else {
			$result = "Nessuna categoria trovata.";
		}
		return $result;
	}

	function addCategoria($idarticolo,$cid)  {
		global $conn;
		$qry = "INSERT INTO categorie_correlate VALUES($idarticolo,$cid);";
		$rs = $conn->Execute($qry);
		if($rs)
		$rs->Close();
	}

	function delCategoria($idarticolo,$cid)  {
		global $conn;
		$qry = "DELETE FROM categorie_correlate WHERE idarticolo=$idarticolo AND cid=$cid;";
		$rs = $conn->Execute($qry);
		if($rs)
		$rs->Close();
	}

	function addCategoriaGruppo($cid_from,$cid) {
		global $conn;
		$qry = "SELECT idarticolo FROM articoli_new WHERE cid=$cid_from;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0) {
			while(!$rs->EOF) {
				$idarticolo = $rs->Fields("idarticolo");
				$qry = "INSERT INTO categorie_correlate VALUES($idarticolo,$cid);";
				$rs2 = $conn->Execute($qry);
				if($rs2)
				$rs2->Close();
				$rs->MoveNext();
			}
			$rs->Close();
		}
		return '<p class="error">La categoria &egrave; stata correlata in blocco!</p>
		<p align="center"><a href="javascript:history.go(-1);">RITORNA</a></p>';
	}

	function update_field($field,$value,$idarticolo)  {
		global $conn;
		$qry = "UPDATE articoli_new SET $field='$value' WHERE idarticolo=$idarticolo;";
		$rs = $conn->Execute($qry);
		if($rs)
		$rs->Close();
		return $qry;
	}

	function getPromozioni($cid)  {
		global $conn;
		$elencoB = "0";
		$elencoV = "0";
		$elencoN = "0";
		switch($cid)  {
			case 2:
				$titolo = "Piscine";
				break;

			case 3:
		  $titolo = "Giardino";
		  break;

			case 267:
		  $titolo = "Casa";
		  break;

			case 4:
		  $titolo = "Sport";
		  break;
		}
		$list = category::getChild($cid,$cid);
		$result = '<table width=750 class=content cellpadding=3 cellspacing=0 border=0>
				 <tr>
				   <td colspan=2 class="error" align="center">ELENCO PROMOZIONI</td>
				 </tr>
				 <tr>
				   <td colspan=2 class="tbtit">Banner '.$titolo.'</td>
				 </tr>';
		$qry = "SELECT idarticolo,titolo1 FROM articoli_new WHERE banner='y' AND cid IN ($list) ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			while(!$rs->EOF)  {
				$elencoB .= ','.$rs->Fields("idarticolo");
				$result .= '<tr>
	      				<td width="500">'.htmlentities($rs->Fields("titolo1")).'</td>
	      				<td align="center"><img src="imgs/ico_delete.gif" alt="Togli dai Banner" onClick="if(confirm(\'Sei sicuro di voler togliere questo articolo dai Banner? Procedere?\')) ajax_del_promozioni(\''.$rs->Fields("idarticolo").'\',\'banner\',\''.$cid.'\')"></td>
		  			  </tr>';
		  $rs->MoveNext();
			}
		}
		$result .= '<tr>
	  				<td colspan=2>Aggiungi articolo per BANNER '.$titolo.':';
		$sql = "SELECT titolo1,idarticolo FROM articoli_new WHERE idarticolo NOT IN ($elencoB) AND cid IN ($list) ORDER BY titolo1 ASC;";
		$rs_menu = $conn->Execute($sql);
		$result .= $rs_menu->GetMenu("idarticolo","",false,false,0,"id='idarticolo_banner' style='width:500px'");
		$rs_menu->Close();
		$result .= '&nbsp;&nbsp;<input type="button" value="AGGIUNGI" onClick="ajax_add_promozioni(\'banner\',\''.$cid.'\')"></td>
	  			  </tr>
				  <tr>
				   <td colspan=2 class="tbtit">Vetrina '.$titolo.'</td>
				 </tr>';
		$qry = "SELECT idarticolo,titolo1 FROM articoli_new WHERE vetrina='y' AND cid IN ($list) ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			while(!$rs->EOF)  {
				$elencoV .= ','.$rs->Fields("idarticolo");
				$result .= '<tr>
	      				<td width="500">'.htmlentities($rs->Fields("titolo1")).'</td>
	      				<td align="center"><img src="imgs/ico_delete.gif" alt="Togli dalla vetrina" onClick="if(confirm(\'Sei sicuro di voler togliere questo articolo dalla Vetrina? Procedere?\')) ajax_del_promozioni(\''.$rs->Fields("idarticolo").'\',\'vetrina\',\''.$cid.'\')"></td>
		  			  </tr>';
		  $rs->MoveNext();
			}
		}
		$result .= '<tr>
	  				<td colspan=2>Aggiungi articolo per VETRINA '.$titolo.':';
		$sql = "SELECT titolo1,idarticolo FROM articoli_new WHERE idarticolo NOT IN ($elencoV) AND cid IN ($list) ORDER BY titolo1 ASC;";
		$rs_menu = $conn->Execute($sql);
		$result .= $rs_menu->GetMenu("idarticolo","",false,false,0,"style='width:500px' id='idarticolo_vetrina'");
		$rs_menu->Close();
		$result .= '&nbsp;&nbsp;<input type="button" value="AGGIUNGI" onClick="ajax_add_promozioni(\'vetrina\',\''.$cid.'\')"></td>
	  			  </tr>
				  <tr>
				   <td colspan=2 class="tbtit">Novit&agrave; '.$titolo.'</td>
				 </tr>';
		$qry = "SELECT idarticolo,titolo1 FROM articoli_new WHERE novita='y' AND cid IN ($list) ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			while(!$rs->EOF)  {
				$elencoN .= ','.$rs->Fields("idarticolo");
				$result .= '<tr>
	      				<td width="500">'.htmlentities($rs->Fields("titolo1")).'</td>
	      				<td align="center"><img src="imgs/ico_delete.gif" alt="Togli dalle Novit&agrave;" onClick="if(confirm(\'Sei sicuro di voler togliere questo articolo dalle Novit&agrave;? Procedere?\')) ajax_del_promozioni(\''.$rs->Fields("idarticolo").'\',\'novita\',\''.$cid.'\')"></td>
		  			  </tr>';
		  $rs->MoveNext();
			}
		}
		$result .= '<tr>
	  				<td colspan=2>Aggiungi articolo per NOVIT&Agrave; '.$titolo.':';
		$sql = "SELECT titolo1,idarticolo FROM articoli_new WHERE idarticolo NOT IN ($elencoN) AND cid IN ($list) ORDER BY titolo1 ASC;";
		$rs_menu = $conn->Execute($sql);
		$result .= $rs_menu->GetMenu("idarticolo","",false,false,0,"style='width:500px' id='idarticolo_novita'");
		$rs_menu->Close();
		$result .= '&nbsp;&nbsp;<input type="button" value="AGGIUNGI" onClick="ajax_add_promozioni(\'novita\',\''.$cid.'\')"></td>
	  			  </tr>
				 </table>';
		return $result;
	}

	function getBuoni()  {
		global $conn;
		$qry = "SELECT idbuono,codice,valore,attivo FROM buoni ORDER BY codice;";
		$rs = $conn->Execute($qry);
		$result = '<div id="dialog_cat"></div><div id="dialog_delcat"></div>
		<div id="dialog_art"></div><div id="dialog_delart"></div>
		<div id="dialog_gruppo"></div><div id="dialog_delgruppo"></div>
		<div id="dialog_user"></div><div id="dialog_deluser"></div>
		<div id="dialog_addbuono"></div>
		<div id="dialog_buono"></div><div id="dialog_delbuono"></div>
		<table width=750 class=content cellpadding=3 cellspacing=0 border=0 align="center">
				 <tr>
				   <td colspan=6 class="error" align="center">BUONI SCONTO</td>
				 </tr>
				 <tr>
				 	<td class="tbtit" width="80">Codice - Valore</td>
				 	<td class="tbtit" width="200">Categorie</td>
				 	<td class="tbtit" width="200">Articoli</td>
				 	<td class="tbtit" width="80">Gruppi</td>
				 	<td class="tbtit" width="100">Utenti</td>
				 	<td class="tbtit">Azioni</td>
				 </tr>';
		if($rs->RecordCount()>0)  {
			while(!$rs->EOF)  {
				$idbuono = $rs->Fields("idbuono");
				$attivo = $rs->Fields("attivo");
				if($attivo == "y")
				$semaforo = "<a href=\"product_new.php?op=disactive_buono&idbuono=$idbuono\"><img src=\"imgs/ico_green.jpg\" border=0 alt=Disattiva></a>";
				else
				$semaforo = "<a href=\"product_new.php?op=active_buono&idbuono=$idbuono\"><img src=\"imgs/ico_red.jpg\" border=0 alt=Attiva></a>";
				$result .= '<tr>
			  				<td><a href="javascript:;" onClick="ajax_del_buono(\''.$idbuono.'\')">'.$rs->Fields("codice").' - '.$rs->Fields("valore").' &euro;</a></td>
							<td>';
				###################### categorie #########################################################
				$qry = "SELECT categorie.cid as cid,categorie.titolo as titolo FROM categorie INNER JOIN buoni_categorie ON categorie.cid=buoni_categorie.cid WHERE idbuono=$idbuono ORDER BY titolo;";
				$rs2 = $conn->Execute($qry);
				if($rs2->RecordCount()>0)  {
			  while(!$rs2->EOF)  {
			  	$result .= '<a href="javascript:;" title="Togli questa categoria" onClick="ajax_del_cat(\''.$idbuono.'\',\''.$rs2->Fields("cid").'\')">'.$rs2->Fields("titolo").'</a><br>';
			  	$rs2->MoveNext();
			  }
			  $rs2->Close();
				} else
				$result .= '&nbsp;';
				$result .= '<a href="javascript:;" onClick="ajax_add_cat(\''.$idbuono.'\')">NUOVO</a></td><td>';
				########################### articoli ####################################################
				$qry = "SELECT articoli_new.idarticolo as idarticolo,articoli_new.titolo1 as titolo FROM articoli_new INNER JOIN buoni_articoli ON articoli_new.idarticolo=buoni_articoli.idarticolo WHERE idbuono=$idbuono ORDER BY titolo;";
				$rs2 = $conn->Execute($qry);
				if($rs2->RecordCount()>0)  {
			  while(!$rs2->EOF)  {
			  	$result .= '<a href="javascript:;" title="Togli questo articolo" onClick="ajax_del_art(\''.$idbuono.'\',\''.$rs2->Fields("idarticolo").'\')">'.$rs2->Fields("titolo").'</a><br>';
			  	$rs2->MoveNext();
			  }
			  $rs2->Close();
				} else
				$result .= '&nbsp;';
				$result .= '<a href="javascript:;" onClick="ajax_add_art(\''.$idbuono.'\')">NUOVO</a></td><td>';
				########################### gruppi ####################################################
				$qry = "SELECT gruppo.idgruppo as idgruppo,gruppo.nome as titolo FROM gruppo INNER JOIN buoni_gruppo ON gruppo.idgruppo=buoni_gruppo.idgruppo WHERE idbuono=$idbuono ORDER BY titolo;";
				$rs2 = $conn->Execute($qry);
				$elenco = "0";
				if($rs2->RecordCount()>0)  {
			  while(!$rs2->EOF)  {
			  	$elenco .= ",".$rs2->Fields("idgruppo");
			  	$result .= '<a href="javascript:;" title="Togli questo gruppo" onClick="ajax_del_gruppo(\''.$idbuono.'\',\''.$rs2->Fields("idgruppo").'\')">'.$rs2->Fields("titolo").'</a><br>';
			  	$rs2->MoveNext();
			  }
			  $rs2->Close();
				} else
				$result .= '&nbsp;';
				$result .= '<a href="javascript:;" onClick="ajax_add_gruppo(\''.$idbuono.'\')">NUOVO</a></td><td>';
				########################### utenti ####################################################
				$qry = "SELECT DISTINCT webuser.idwebuser as idwebuser,webuser.cognome as titolo FROM ((webuser INNER JOIN buoni_webuser ON webuser.idwebuser=buoni_webuser.idwebuser) INNER JOIN contatti ON webuser.mail=contatti.mail) WHERE idbuono=$idbuono AND contatti.idgruppo NOT IN ($elenco) ORDER BY titolo;";
				$rs2 = $conn->Execute($qry);
				if($rs2->RecordCount()>0)  {
			  while(!$rs2->EOF)  {
			  	$result .= '<a href="javascript:;" title="Togli questo utente" onClick="ajax_del_user(\''.$idbuono.'\',\''.$rs2->Fields("idwebuser").'\')">'.$rs2->Fields("titolo").'</a><br>';
			  	$rs2->MoveNext();
			  }
			  $rs2->Close();
				} else
				$result .= '&nbsp;';
				$result .= '<a href="javascript:;" onClick="ajax_add_user(\''.$idbuono.'\')">NUOVO</a></td>
			<td align="center"><a href="javascript:;" onClick="ajax_mod_codice(\''.$idbuono.'\',\''.$rs->Fields("codice").'\',\''.$rs->Fields("valore").'\')"><img src="imgs/ico_edit.gif" border="0"></a>&nbsp;&nbsp;'.$semaforo.'</td>
		</tr>';
				$rs->MoveNext();
			}
			$rs->Close();
		}
		$result .= '<tr>
				   <td colspan=6 class="error"><a href="javascript:;" onClick="ajax_add_codice()">NUOVO CODICE SCONTO</a></td>
				 </tr></table>';
		return $result;
	}

	function getBuono($idbuono)  {
		global $conn;
		$qry = "SELECT * FROM buoni WHERE idbuono=$idbuono;";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error[0] = $rs->Fields("idbuono");
			$error[1] = $rs->Fields("codice");
			$error[2] = $rs->Fields("valore");
			$error[3] = $rs->Fields("attivo");
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function addBuono($codice,$valore)  {
		global $conn;
		$qry = "INSERT INTO buoni VALUES(NULL,'$codice',$valore,'y');";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function updBuono($codice,$valore,$idbuono)  {
		global $conn;
		$qry = "UPDATE buoni SET codice='$codice',valore=$valore WHERE idbuono=$idbuono;";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function activeBuono($idbuono)  {
		global $conn;
		$qry = "UPDATE buoni SET attivo='y' WHERE idbuono=$idbuono;";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function disactiveBuono($idbuono)  {
		global $conn;
		$qry = "UPDATE buoni SET attivo='n' WHERE idbuono=$idbuono;";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function delBuono($idbuono)  {
		global $conn;
		$qry = "DELETE FROM buoni WHERE idbuono=$idbuono;";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$qry = "DELETE FROM buoni_categorie WHERE idbuono=$idbuono;";
			$rs2 = $conn->Execute($qry);
			if($rs2)
			$rs2->Close();
			$qry = "DELETE FROM buoni_articoli WHERE idbuono=$idbuono;";
			$rs2 = $conn->Execute($qry);
			if($rs2)
			$rs2->Close();
			$qry = "DELETE FROM buoni_gruppo WHERE idbuono=$idbuono;";
			$rs2 = $conn->Execute($qry);
			if($rs2)
			$rs2->Close();
			$qry = "DELETE FROM buoni_webuser WHERE idbuono=$idbuono;";
			$rs2 = $conn->Execute($qry);
			if($rs2)
			$rs2->Close();
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function addBuonoCat($idbuono,$cid)  {
		global $conn;
		$qry = "INSERT INTO buoni_categorie VALUES($idbuono,$cid);";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function delBuonoCat($idbuono,$cid)  {
		global $conn;
		$qry = "DELETE FROM buoni_categorie WHERE idbuono=$idbuono AND cid=$cid;";
		$rs2 = $conn->Execute($qry);
		if($rs2)
		$rs2->Close();
		return 0;
	}

	function addBuonoArt($idbuono,$idarticolo)  {
		global $conn;
		$qry = "INSERT INTO buoni_articoli VALUES($idbuono,$idarticolo);";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function delBuonoArt($idbuono,$idarticolo)  {
		global $conn;
		$qry = "DELETE FROM buoni_articoli WHERE idbuono=$idbuono AND idarticolo=$idarticolo;";
		$rs2 = $conn->Execute($qry);
		if($rs2)
		$rs2->Close();
		return 0;
	}

	function addBuonoGruppo($idbuono,$idgruppo)  {
		global $conn;
		$qry = "INSERT INTO buoni_gruppo VALUES($idbuono,$idgruppo);";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$qry = "SELECT DISTINCT webuser.idwebuser as idwebuser FROM
		  webuser INNER JOIN contatti ON webuser.mail=contatti.mail WHERE contatti.idgruppo=$idgruppo;";
			$rs2 = $conn->Execute($qry);
			if($rs2->RecordCount()>0)  {
		  while(!$rs2->EOF)  {
		  	articoli::addBuonoWebuser($idbuono,$rs2->Fields("idwebuser"));
		  	$rs2->MoveNext();
		  }
		  $rs2->Close();
			}
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function delBuonoGruppo($idbuono,$idgruppo)  {
		global $conn;
		$qry = "DELETE FROM buoni_gruppo WHERE idbuono=$idbuono AND idgruppo=$idgruppo;";
		$rs2 = $conn->Execute($qry);
		if($rs2) {
			$qry = "SELECT DISTINCT webuser.idwebuser as idwebuser FROM
		  webuser INNER JOIN contatti ON webuser.mail=contatti.mail WHERE contatti.idgruppo=$idgruppo;";
			$rs = $conn->Execute($qry);
			if($rs->RecordCount()>0)  {
		  while(!$rs->EOF)  {
		  	articoli::delBuonoWebuser($idbuono,$rs->Fields("idwebuser"));
		  	$rs->MoveNext();
		  }
		  $rs->Close();
			}
			$error = 0;
			$rs2->Close();
		}
		return 0;
	}

	function addBuonoWebuser($idbuono,$idwebuser)  {
		global $conn;
		$qry = "INSERT INTO buoni_webuser VALUES($idbuono,$idwebuser,'n');";
		$rs = $conn->Execute($qry);
		if($rs)  {
			$error = 0;
			$rs->Close();
		} else
		$error = 1;
		return $error;
	}

	function delBuonoWebuser($idbuono,$idwebuser)  {
		global $conn;
		$qry = "DELETE FROM buoni_webuser WHERE idbuono=$idbuono AND idwebuser=$idwebuser;";
		$rs2 = $conn->Execute($qry);
		if($rs2)
		$rs2->Close();
		return 0;
	}

	function json_articoli($cid="")  {
		global $conn;
		if($cid!="") $where = "WHERE cid=$cid";
		$qry = "SELECT idarticolo,titolo1 FROM articoli_new $where ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$json = "{'rows':[";
			$rc = false;
			while(!$rs->EOF)  {
				if($rc) $json.=",";
				$json .= "{'idarticolo':'".$rs->Fields("idarticolo")."','titolo':'".htmlentities(addslashes($rs->Fields("titolo1")))."'}";
				$rc = true;
			 $rs->MoveNext();
			}
			$json .= "]}";
			$rs->Close();
		}
		return $json;
	}

	function getCsv($cid="")  {
		global $conn,$percorso,$lang;
		if($cid!="") {
			$list_cid = category::getChild($cid,$cid);
			$qry_cid = "AND cid IN ($list_cid)";
		}
		$qry = "SELECT idarticolo,cid,codice,titolo1,titolo2,descrizione,image_big,video,scheda,prezzo1,prezzo2,spedizione,spedizione2,promozione,vetrina,novita,import FROM articoli_new WHERE attivo='y' AND lang='$lang' $qry_cid ORDER BY cid,ordine;";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$content = "categoria;titolo;codice_prodotto;sottotitolo;descrizione_articolo;URL_immagine;URL_video;prezzo_intero;prezzo_scontato;spedizione;spedizione_2;promozione;vetrina;novita\n";
			while(!$rs->EOF)  {
				if($cid2!=$rs->Fields("cid")) {
		   $cid2 = $rs->Fields("cid");
		   $cat = new category($cid2);
				}
				$categoria = articoli::getPercorso($cid2,$cat->titolo);
				if($rs->Fields("import")==1)
				$folder = "/immagini-piscine";
				else
				$folder = "/gestione/imgs_prodotti/".$rs->Fields("idarticolo");
				if($rs->Fields("image_big")!="")
				$image = 'http://www.bsvillage.com'.$folder.'/'.str_replace(" ","_",$rs->Fields("image_big"));
				else
				$image = "";
				if($rs->Fields("video")!="")
				$video = 'http://www.bsvillage.com/gestione/imgs_prodotti/'.$rs->Fields("idarticolo").'/'.$rs->Fields("video");
				else
				$video = "";
				if($rs->Fields("promozione")=='y')
				$prom = "Si";
				else
				$prom = "No";
				if($rs->Fields("vetrina")=='y')
				$vetrina = "Si";
				else
				$vetrina = "No";
				if($rs->Fields("novita")=='y')
				$novita = "Si";
				else
				$novita = "No";
		  $rs->MoveNext();
		  $content .= '"'.addslashes($categoria).'";"'.addslashes($rs->Fields("titolo1")).'";"'.addslashes($rs->Fields("codice")).'";"'.addslashes($rs->Fields("titolo2")).'";"'.addslashes($rs->Fields("descrizione")).'";"'.$image.'";"'.$video.'";"'.number_format($rs->Fields("prezzo1"),2,",","").'";"'.number_format($rs->Fields("prezzo2"),2,",","").'";"'.number_format($rs->Fields("spedizione"),2,",","").'";"'.number_format($rs->Fields("spedizione2"),2,",","").'";"'.$prom.'";"'.$vetrina.'";"'.$novita.'"'."\n";
			}
			$rs->Close();
			header("Content-type:text/csv");
			header("Content-Disposition:attachment;filename=articoli.csv");
			echo $content;
		}
	}

	function getRSS($cid)  {
		global $conn;
		switch($cid)  {
			case 2:
				$titolo = "Piscine";
				$folder = "piscine";
				break;

			case 3:
		  $titolo = "Giardino";
		  $folder = "giardino";
		  break;

			case 267:
		  $titolo = "Casa";
		  $folder = "casa";
		  break;

			case 4:
		  $titolo = "Sport";
		  $folder = "sport-fitness";
		  break;
		}
		$list_cid = category::getChild($cid,$cid);
		$qry = "SELECT idarticolo,cid,codice,titolo1,titolo2,descrizione,image_big,video,scheda,prezzo1,prezzo2,spedizione,spedizione2,promozione,vetrina,novita,hidden,fornitore FROM articoli_new WHERE attivo='y' AND cid IN ($list_cid) ORDER BY idarticolo DESC;";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0)  {
			$content = '<?xml version="1.0" encoding="iso-8859-1" ?>
<rss version="2.0">
<channel><title>BSVillage - '.$titolo.'</title>
<link>http://www.bsvillage.com/rss.php?cid='.$cid.'</link>
<description>BSVillage RSS Feed .</description>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<managingEditor>info@bsvillage.com (BSVillage.com) </managingEditor>
<webMaster>info@bsvillage.com (BSVillage.com) </webMaster>
<language>it-it</language>
<image>
<title>BSVillage - '.$titolo.'</title>
<link>http://www.bsvillage.com</link>
<url>http://www.bsvillage.com/images/loghi/bs-piscine.gif</url>
</image>';
			while(!$rs->EOF)  {

				$immagine_pagina = 'http://www.bsvillage.com/gestione/imgs_prodotti/'.$rs->Fields("idarticolo").'/'.str_replace(" ","_",$rs->Fields("image_big"));
				/*$immagine_pagina = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $rs->Fields("descrizione"), $matches);
				$immagine_pagina = $matches [1][0];*/
				list($listino,$scontato,$spedizione) = articoli::getPrezzo($rs->Fields("idarticolo"),$rs->Fields("cid"),$rs->Fields("prezzo1"),$rs->Fields("prezzo2"),10,$rs->Fields("fornitore"));
				$permalink = fromTitToUrl($rs->Fields("hidden"));
				$description = 'Prezzo: '.number_format($listino,2,",","").' Euro
Prezzo scontato: '.number_format($scontato,2,",","").' Euro';
		  $content .= '<item>
<title><![CDATA['.$rs->Fields("titolo1").']]></title>
<link>http://www.bsvillage.com/'.$permalink.'/'.$rs->Fields("idarticolo").'</link>
<description><![CDATA[<img src="'.$immagine_pagina.'" alt="" height="150" /> Cod. '.$rs->Fields("codice").$description.']]></description>
<guid isPermaLink="true">http://www.bsvillage.com/'.$permalink.'/'.$rs->Fields("idarticolo").'</guid>
<category></category>
<pubDate>'.date('D, d M Y H:i:s').'</pubDate>
</item>';
		  $rs->MoveNext();
			}
			$content .= '<copyright>Copyright (c) BSVillage 2009</copyright>
</channel>
</rss>';
			$rs->Close();
		}
		header("Content-type:text/xml");
		echo $content;
	}

	function import($csv) {
		global $conn,$path_tmp;
		if($csv['name']!="") {
			$filename = $path_tmp.$csv['name'];
			move_uploaded_file($csv['tmp_name'],$filename);
		}
		$row = 1;
		$result = "INSERT INTO articoli_new (`idarticolo`, `cid`, `codice`, `titolo1`, `titolo2`, `descrizione`, `image_tmb`, `image`, `image_big`, `prezzo1`, `prezzo2`, `spedizione`, `spedizione2`, `promozione`, `vetrina`, `novita`, `minimo`, `attivo`, `lang`, `ordine`, `peso`, `video`, `scheda`, `hit`, `disp`, `banner`, `tagtitle`, `tagkey`, `tagdesc`, `metatitle`, `metakey`, `metadesc`, `hidden`, `correlato1`, `correlato2`, `correlato3`, `import`,`fornitore`,`costo`) VALUES";
		if(($handle = fopen($filename, "r")) !== FALSE) {
			while (($data = fgetcsv($handle, 5000, ";")) !== FALSE) {
				if($row > 1) {
					$num = count($data);
					$image = "";
					if(file_exists($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$data[1].".jpg")) {
						$image = $_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$data[1].".jpg";
						$myimage = $data[1].".jpg";
					} elseif(file_exists($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$data[1].".JPG")) {
						$image = $_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$data[1].".JPG";
						$myimage = $data[1].".JPG";
					} else {
						$myimage = "";
						$image = "";
					}
					if($image!="") {
						$obj = new Image($image);
						$image2 = $data[1].".jpg";
						$image_gal = $data[1]."_6.jpg";
						$tmb = "tmb_".$image2;
						$big = "big_".$image2;
						$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$image_gal, 80,0,$obj->src_width);
						if($obj->src_width > 200)
						$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$big, 80,0,200);
						else
						$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$big, 80,0,$obj->src_width);
						$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$tmb, 60,0,40);
						$obj->SaveProportionateImage2($_SERVER['DOCUMENT_ROOT']."/immagini-piscine/".$image2, 60,0,80);
					} else {
						$tmb = "";
						$big = "";
					}
					if($row>2 && $data[0]!="") $result.=",";
					if($data[0]!="")
					$result .= "(NULL,".$data[0].",'".$data[1]."','".addslashes($data[2])."','".addslashes($data[3])."','".addslashes($data[4])."','$tmb','$myimage','$big',".str_replace(",",".",$data[6]).",".str_replace(",",".",$data[7]).",".str_replace(",",".",$data[8]).",".str_replace(",",".",$data[9]).",'y','n','n',1,'y','ita',0,0,'','".addslashes($data[5])."',0,50,'n','".addslashes($data[2])." | BSVillage.com','".addslashes($data[2])."','".addslashes($data[4])."','','','','".addslashes($data[2])."','".$data[10]."','".$data[11]."','".$data[12]."',1,'".$data[13]."',".$data[14].")";
				}
				$row++;
			}
			fclose($handle);
			@unlink($filename);
		}
		//return $result;
		$rs = $conn->Execute($result);
		if($rs)
		return "Importazione completata con successo!";
		else
		return "Problemi durante l'importazione!<br>Errore: ".$conn->ErrorMsg();
	}

	function importOrdineMinimo($csv) {
		global $conn,$path_tmp;
		if($csv['name']!="") {
			$filename = $path_tmp.$csv['name'];
			move_uploaded_file($csv['tmp_name'],$filename);
		}
		$row = 1;
		$count = 0;
		if(($handle = fopen($filename, "r")) !== FALSE) {
			while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
				if($row > 1) {
					$num = count($data);
					if($data[1]!="" && $data[0]!="" && $data[2]!="")
					$codice = trim($data[1]);
					$result = "UPDATE articoli_new SET fornitore='".$data[0]."',minimo=".$data[2]." WHERE codice='$codice';";
					$rs = $conn->Execute($result);
					if($rs)
					$count++;
					else
					return "Problemi durante l'importazione!<br>Errore: ".$conn->ErrorMsg();
				}
				$row++;
			}
			fclose($handle);
			@unlink($filename);
		}
		//return $result;
		return "Sono stati aggiornati $count articoli!";
	}

	function getManuale($mail,$nome) {
		global $conn,$adminmail;
		$subject = "La tua guida gratuita da www.bsvillage.com";
		$message = "Ciao $nome,
		hai ricevuto questa email perche'  hai inserito i tuoi dati per ottenere la Guida Gratuita:
 
\"Consigli e Segreti per la Manutenzione della tua Piscina\"
 
Come protrai notare  guida si trova in allegato a questa email, se dovessi avere problemi nello scaricare l'allegato rispondi semplicemente a questa email!
 
Torna presto a farci visita!
Businesshop Piscine
 

Businesshop, via Pascal 100, Reggio Emilia, 07 42100, ITALY ";
		#################################### invio mail con phpmailer #############################
		require_once("class.phpmailer.php");
		$omail = new PHPMailer();
		$omail->IsSMTP();                    // attiva l'invio tramiteSMTP
		$omail->Mailer = "smtp";
		$omail->Host = "195.225.169.96";
		$omail->Username = "max@media-tek.it";
		$omail->Password = "FrAnCy478";
		$omail->From     = $adminmail;
		$omail->FromName = "BSVILLAGE BUSINESS SHOP";
		$omail->SMTPAuth = true;
		//$omail->IsHTML(true);
		//$omail->SMTPDebug = true;
		$omail->Subject  =  $subject;
		$omail->Body     =  $message;
		$omail->AddAttachment($_SERVER['DOCUMENT_ROOT']."/download/Manuale_Manutenzione_Piscina.pdf");
		$omail->AddAddress($mail);
		if($omail->Send()) {}
	}

	function search($search)  {
		global $conn;
		if(strlen($search)>3)  {
			$qry = "SELECT idarticolo,cid,titolo1,ordine,attivo,banner,prezzo1,prezzo2,spedizione,spedizione2,minimo,disp,codice,costo,fornitore,vetrina,promozione,novita,produttore,image_tmb, MATCH(codice,titolo1,titolo2,descrizione,fornitore,produttore) AGAINST('$search' IN BOOLEAN MODE) AS attinenza FROM articoli_new WHERE giardino=0 AND MATCH(codice,titolo1,titolo2,descrizione,fornitore,produttore) AGAINST('$search' IN BOOLEAN MODE) ORDER BY attinenza desc";
			$qry_tot = "SELECT idarticolo, MATCH(codice,titolo1,titolo2,descrizione,fornitore,produttore) AGAINST('$search' IN BOOLEAN MODE) AS attinenza FROM articoli_new WHERE giardino=0 AND MATCH(codice,titolo1,titolo2,descrizione,fornitore,produttore) AGAINST('$search' IN BOOLEAN MODE);";
		} else {
			$qry = "SELECT idarticolo,cid,titolo1,ordine,attivo,banner,prezzo1,prezzo2,spedizione,spedizione2,minimo,disp,codice,costo,fornitore,vetrina,promozione,novita,produttore,image_tmb FROM articoli_new WHERE giardino=0 AND (codice LIKE '%$search%' OR titolo1 LIKE '%$search%' OR titolo2 LIKE '%$search%' OR descrizione LIKE '%$search%' OR fornitore LIKE '%$search%' OR produttore LIKE '%$search%' OR produttore LIKE '%$search%') ORDER BY titolo1";
			$qry_tot = "SELECT idarticolo FROM articoli_new WHERE giardino=0 AND (codice LIKE '%$search%' OR titolo1 LIKE '%$search%' OR titolo2 LIKE '%$search%' OR descrizione LIKE '%$search%' OR fornitore LIKE '%$search%' OR produttore LIKE '%$search%');";
		}
		//die($qry_tot);
		$rs = $conn->Execute($qry);
		$content = "<table width=100% class=content cellpadding=3 cellspacing=0 border=0>
				<tr>
				   <td colspan=16 style=\"color:blue\">RICERCA PER '$search'</td>
				 </tr>
				 <tr>
				   <td colspan=16 style=\"color:red\">Per modificare gli importi cliccare sul valore da aggiornare, fare la modifica e cliccare fuori dalla tabella.</td>
				 </tr>
				 <tr>
				   	<td width=20>&nbsp;</td>
				   	<td width=350><b>Articolo</b></td>
				   	<td width=50><b>Codice</b></td>
				   	<td width=50><b>Prezzo(&euro;)</b></td>
				   	<td width=50><b>Scontato(&euro;)</b></td>
				   	<td width=50><b>Costo IVA incl.(&euro;)</b></td>
				   	<td width=50><b>Spediz.(&euro;)</b></td>
				   	<td width=50><b>Sec. Prod.(&euro;)</b></td>
				   	<td width=50><b>Ricarico.(%)</b></td>
				   	<td width=50><b>Min.</b></td>
				   	<td width=50><b>Disp.</b></td>
				   	<td width=50><b>Vetrina</b></td>
				   	<td width=50><b>Promozione</b></td>
				   	<td width=50><b>Novit&agrave;</b></td>
				   	<td width=50><b>Fornitore</b></td>
				   	<td width=50><b>Produttore</b></td>
					<td></td>
				   	<td></td>
				   	<td></td>
				   	<td></td>
				   	<td></td>
				   	<td></td>
				   </tr>";
		if($rs->RecordCount() > 0)  {
			while(list($idarticolo,$cid,$titolo1,$ordine,$attivo,$banner,$prezzo1,$prezzo2,$spedizione,$spedizione2,$minimo,$disp,$codice,$costo,$fornitore,$vetrina,$promozione,$novita,$produttore,$image_tmb) = @array_values($rs->FetchRow()))  {
				#########################################################################################
				if($attivo == "y")
				$semaforo = "<a href=\"product_new.php?op=disactive&idarticolo=$idarticolo&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/ico_green.jpg\" border=0 alt=Disattiva></a>";
				else
				$semaforo = "<a href=\"product_new.php?op=active&idarticolo=$idarticolo&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/ico_red.jpg\" border=0 alt=Attiva></a>";
				#########################################################################################
				if($banner == "y")
				$banner = "<a href=\"product_new.php?op=bannerOut&idarticolo=$idarticolo&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/banner.jpg\" border=0 alt=\"In banner destra\"></a>";
				else
				$banner = "<a href=\"product_new.php?op=bannerIn&idarticolo=$idarticolo&cid=$cid&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=\"imgs/nobanner.jpg\" border=0 alt=\"No banner destra\"></a>";
				#######################################################################################
				if($fornitore=="") $fornitore = "&nbsp;";
				if($produttore=="") $produttore = "&nbsp;";
				$costo > 0 ? $ricarico = ((($prezzo2 + $spedizione) / $costo) - 1)*100 : $ricarico=0;
				if($image_tmb!="") {
					file_exists("imgs_prodotti/$idarticolo/$image_tmb") ? $image = '<img src="imgs_prodotti/'.$idarticolo.'/'.$image_tmb.'" />' : $image = '<img src="../immagini-piscine/'.$image_tmb.'" />';
				}
				$content .= "<tr>
				   <td class=content width=20>$image</td>
				   <td><div id=\"titolo1_$idarticolo\" onClick=\"ajax_edit('titolo1_$idarticolo')\">$titolo1</div></td>
				   <td><div id=\"codice_$idarticolo\" onClick=\"ajax_edit('codice_$idarticolo')\">$codice</div></td>
				   <td><div id=\"prezzo1_$idarticolo\" onClick=\"ajax_edit('prezzo1_$idarticolo')\">$prezzo1</div></td>
				   	<td><div id=\"prezzo2_$idarticolo\" onClick=\"ajax_edit('prezzo2_$idarticolo')\">$prezzo2</div></td>
				   	<td><div id=\"costo_$idarticolo\" onClick=\"ajax_edit('costo_$idarticolo')\">$costo</div></td>
				   	<td><div id=\"spedizione_$idarticolo\" onClick=\"ajax_edit('spedizione_$idarticolo')\">$spedizione</div></td>
				   	<td><div id=\"spedizione2_$idarticolo\" onClick=\"ajax_edit('spedizione2_$idarticolo')\">$spedizione2</div></td>
				   	<td><div id=\"ricarico_$idarticolo\" >".number_format($ricarico,2)."</div></td>
				   	<td><div id=\"minimo_$idarticolo\" onClick=\"ajax_edit('minimo_$idarticolo')\">$minimo</div></td>
				   	<td><div id=\"disp_$idarticolo\" onClick=\"ajax_edit('disp_$idarticolo')\">$disp</div></td>
				   	<td><div id=\"vetrina_$idarticolo\" onClick=\"ajax_edit('vetrina_$idarticolo')\">$vetrina</div></td>
				   	<td><div id=\"promozione_$idarticolo\" onClick=\"ajax_edit('promozione_$idarticolo')\">$promozione</div></td>
				   	<td><div id=\"novita_$idarticolo\" onClick=\"ajax_edit('novita_$idarticolo')\">$novita</div></td>
				   	<td><div id=\"fornitore_$idarticolo\" onClick=\"ajax_edit('fornitore_$idarticolo')\">$fornitore</div></td>
				   	<td><div id=\"produttore_$idarticolo\" onClick=\"ajax_edit('produttore_$idarticolo')\">$produttore</div></td>
				   <td bgcolor=#DFDFDF>$up</td>
				   <td bgcolor=#DFDFDF>$down</td>
				   <td width=20px bgcolor=\"#DFDFDF\"><a href=\"product_new.php?cid=$cid&op=product&idarticolo=$idarticolo&percorso=$percorso\"><img src=imgs/ico_edit.gif width=16 height=16 alt=\"modifica\" border=0></a></td>
				   <td width=20px bgcolor=\"#DFDFDF\"><a href=\"product_new.php?op=del_art&idarticolo=$idarticolo&currentpage=$currentpage&percorso=".urlencode($percorso)."\" onclick=\"return confirm('Sei sicuro di voler eliminare l\'articolo cliccato?');\"><img src=imgs/ico_delete.gif width=16 height=16 alt=\"elimina\" border=0></a></td>
				   <td width=20px bgcolor=\"#DFDFDF\"><a href=\"product_new.php?op=duplica&idarticolo=$idarticolo&currentpage=$currentpage&percorso=".urlencode($percorso)."\"><img src=imgs/duplica.jpg width=16 height=16 alt=\"Duplica\" border=0></a></td>
				   <td width=50 bgcolor=#DFDFDF>$banner</td>
				   <td width=20 bgcolor=#DFDFDF>$semaforo</td>";
				$content .= "</tr>";
			}
		}
		$rs->Close();
		$content .= "</table>";
		return $content;
	}

	function getAttributiRicerca() {
		global $conn;
		$qry = "SELECT id,nome FROM attributi_categorie WHERE cid=".$this->cid.";";
		$rs = esegui_queryRs($qry);
		if($rs->RecordCount()==0) {
			$cat = new category($this->cid);
			$cid = $cat->idfather;
			$qry = "SELECT id,nome FROM attributi_categorie WHERE cid=".$cid.";";
			$rs = esegui_queryRs($qry);
		}
		if($rs->RecordCount()>0) {
			$result = '<div>';
			while(!$rs->EOF) {
				$qry = "SELECT valore FROM attributi_categorie_articoli WHERE idarticolo=$this->idarticolo AND id=".$rs->Fields("id").";";
				$rs2 = esegui_queryRs($qry);
				$result .= '<label>'.$rs->Fields("nome").':</label><input type="text" size="30" name="attributo['.$rs->Fields("id").']" value="'.$rs2->Fields("valore").'"><br>';
				$rs2->Close();
				$rs->MoveNext();
			}
			$rs->Close();
			$result .= '</div>';
		}
		return $result;
	}
	
    function getIdValore($idattributo) {
    	global $conn;
      $rs = $conn->Execute("SELECT idvalore FROM articolo_attributo WHERE idattributo=$idattributo AND idarticolo=$this->idarticolo;");
	  $valore = array();
	  while(!$rs->EOF) {
	  	array_push($valore,$rs->Fields("idvalore"));
	  	$rs->MoveNext();
	  }
	  return $valore;
	}
	
	function listSconti() {
		global $conn;
		  $qry = "SELECT id,titolo,sconto,DATE_FORMAT(dal,'%d/%m/%Y') as start,DATE_FORMAT(al,'%d/%m/%Y') as end,
		  CASE tipo WHEN 0 THEN 'PREZZO LISTINO' WHEN 1 THEN 'PREZZO SCONTATO' WHEN 2 THEN 'ENTRAMBI I PREZZI' 
		  WHEN 3 THEN 'SPEDIZIONE' END as tipo 
		  FROM sconti WHERE giardino=0 ORDER BY titolo;";
		  $rs = esegui_queryRs($qry);
		  $result = '<table class="content" cellpadding="2" width="700">
							<tr>
							  <td class="error" colspan="6" align="center">ELENCO SCONTI ATTIVI</td>
							</tr>
							<tr>
							  <th width="150">NOME</th>
							  <th width="50">SCONTO</th>
							  <th width="50">DAL</th>
							  <th width="50">AL</th>
							  <th width="100">TIPO</th>
							  <th></th>
							</tr>';
		  if($rs->RecordCount()>0) {
			while(!$rs->EOF) {
			  $result .= '<tr>
			  				<td>'.utf8_encode($rs->Fields("titolo")).'</td>
			  				<td>'.$rs->Fields("sconto").'</td>
			  				<td>'.$rs->Fields("start").'</td>
			  				<td>'.$rs->Fields("end").'</td>
			  				<td>'.$rs->Fields("tipo").'</td>
			  				<td align="center"><a href="javascript:;" onClick="editSconto('.$rs->Fields("id").');"><img src="imgs/ico_edit.gif" border="0"></a>&nbsp;&nbsp;<a href="javascript:;" onClick="delSconto('.$rs->Fields("id").');"><img src="imgs/ico_delete.gif" border="0"></a></td>
			  			  </tr>';
			  $rs->MoveNext();
			}
			$rs->Close();
		  }
		$result .= '</table>';
		return $result;
	}
	
	function saveSconto($par) {
	  global $conn;
	  list($g,$m,$a) = explode("/",$par->dal);
	  $dal = "$a-$m-$g";
	  list($g,$m,$a) = explode("/",$par->al);
	  $al = "$a-$m-$g";
	  $qry = "INSERT INTO sconti VALUES(NULL,'$dal','$al','".addslashes($par->titolo)."',$par->sconto,$par->spedizione,'$par->fornitore',0);";
	  //die($qry);
	  $error = esegui_queryInsert($qry);
	  if($par->cids=="0") {
		  	//ARTICOLI
		  	if(is_array($par->idarticolo)) {
		  	  foreach ($par->idarticolo as $idarticolo) {
		  		$conn->Execute("INSERT INTO sconti_articoli VALUES($error,$idarticolo)");
		  	  }	
		  	} else
		  		$conn->Execute("INSERT INTO sconti_articoli VALUES($error,$par->idarticolo)");
		  } else {
		  	//CATEGORIE
		  	if(is_array($par->cids)) {
		  	  foreach ($par->cids as $cid) {
		  		$conn->Execute("INSERT INTO sconti_categorie VALUES($error,$cid)");
		  	  }
		  	} else
		  	   $conn->Execute("INSERT INTO sconti_categorie VALUES($error,$par->cids)"); 
		  }
	}
	
	function updateSconto($par) {
		global $conn;
		list($g,$m,$a) = explode("/",$par->dal);
		  $dal = "$a-$m-$g";
		  list($g,$m,$a) = explode("/",$par->al);
		  $al = "$a-$m-$g";
		  $qry = "UPDATE sconti SET dal='$dal',al='$al',titolo='".addslashes($par->titolo)."',sconto=$par->sconto,tipo=$par->tipo,fornitore='$par->fornitore' WHERE id=$par->id;";
		  //die($qry);
		  $error = esegui_queryUpd($qry);
		  $conn->Execute("DELETE FROM sconti_categorie WHERE id=$par->id");
		  $conn->Execute("DELETE FROM sconti_articoli WHERE id=$par->id");
		  if($par->cids=="0") {
		  	//ARTICOLI
		  	if(is_array($par->idarticolo)) {
		  	  foreach ($par->idarticolo as $idarticolo) {
		  		$conn->Execute("INSERT INTO sconti_articoli VALUES($par->id,$idarticolo)");
		  	  }	
		  	} else
		  		$conn->Execute("INSERT INTO sconti_articoli VALUES($par->id,$par->idarticolo)");
		  } else {
		  	//CATEGORIE
		  	if(is_array($par->cids)) {
		  	  foreach ($par->cids as $cid) {
		  		$conn->Execute("INSERT INTO sconti_categorie VALUES($par->id,$cid)");
		  	  }
		  	} else
		  	   $conn->Execute("INSERT INTO sconti_categorie VALUES($par->id,$par->cids)"); 
		  }
	} 
	
	function deleteSconto($id) {
		global $conn;
		$conn->Execute("DELETE FROM sconti WHERE id=$id;");
		$conn->Execute("DELETE FROM sconti_categorie WHERE id=$id");
		$conn->Execute("DELETE FROM sconti_articoli WHERE id=$id");
	}
	
	function getSconto($id) {
		global $conn;
		$qry = "SELECT id,titolo,sconto,tipo,DATE_FORMAT(dal,'%d/%m/%Y') as start,DATE_FORMAT(al,'%d/%m/%Y') as end,fornitore FROM 
		sconti WHERE id=$id;";
		$rs = esegui_queryRs($qry);
		if($rs->RecordCount()>0) {
			$json = '{"id":'.$rs->Fields("id").',"titolo":'.json_encode($rs->Fields("titolo")).',
			"sconto":"'.$rs->Fields("sconto").'","dal":"'.$rs->Fields("start").'","al":"'.$rs->Fields("end").'"
			,"tipo":'.$rs->Fields("tipo").',"fornitore":'.json_encode($rs->Fields("fornitore")).'';
			$cids = $conn->Execute("SELECT cid FROM sconti_categorie WHERE id=".$rs->Fields("id"));
			if($cids->RecordCount()>0) {
			  $json .= ',"idarticolo":[],"cids":[';
			  $i = 1;
			  while(!$cids->EOF) {
			  	if($i>1) $json.=',';
			  	$json .= $cids->Fields("cid");
			  	$i++;
			  	$cids->MoveNext();
			  }
			  $json .= ']';	
			} else {
				$idarticolo = $conn->Execute("SELECT DISTINCT a.idarticolo as idarticolo,a.cid as cid FROM sconti_articoli s 
				INNER JOIN articoli_new a ON s.idarticolo=a.idarticolo WHERE id=".$rs->Fields("id"));
				if($idarticolo->RecordCount()>0) {
				  $json .= ',"cids":[],cid:'.$idarticolo->Fields("cid").',"idarticolo":[';
				  $i = 1;
				  while(!$idarticolo->EOF) {
				  	if($i>1) $json.=',';
				  	$json .= $idarticolo->Fields("idarticolo");
				  	$i++;
				  	$idarticolo->MoveNext();
				  }
				  $json .= ']';		
				} else {
					$json .= ',"cids":[],cid:"","idarticolo":[]';
				}
			}
			$json .= '}';
			$rs->Close();
		}
		return $json;
	}
	
	function getPrezzo($idarticolo,$cid,$listino,$scontato,$spedizione,$fornitore) {
		global $conn;
		$qry = "SELECT s.sconto as sconto,s.tipo as tipo FROM sconti s INNER JOIN sconti_articoli sa ON 
		s.id=sa.id WHERE sa.idarticolo=$idarticolo AND s.dal <= NOW() AND s.al >= NOW();";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0) {
			switch($rs->Fields("tipo")) {
				case 0:
					$listino = $listino + round($listino / 100 * $rs->Fields("sconto"),2);
					break;
					
				case 1:
					$scontato = $scontato + round($scontato / 100 * $rs->Fields("sconto"),2);
					break;
					
				case 2:
					$scontato = $scontato + round($scontato / 100 * $rs->Fields("sconto"),2);
					$listino = $listino + round($listino / 100 * $rs->Fields("sconto"),2);
					break;
					
				case 3:
					$spedizione = $spedizione + round($spedizione / 100 * $rs->Fields("sconto"),2);
					break;
			}
			$rs->Close();
		} else {
			$qry = "SELECT s.sconto as sconto,s.tipo as tipo FROM sconti s INNER JOIN sconti_categorie sa ON 
			s.id=sa.id WHERE sa.cid=$cid AND s.dal <= NOW() AND s.al >= NOW();";
			$rs = $conn->Execute($qry);
			if($rs->RecordCount()>0) {
				switch($rs->Fields("tipo")) {
					case 0:
						$listino = $listino + round($listino / 100 * $rs->Fields("sconto"),2);
						break;
						
					case 1:
						$scontato = $scontato + round($scontato / 100 * $rs->Fields("sconto"),2);
						break;
						
					case 2:
						$scontato = $scontato + round($scontato / 100 * $rs->Fields("sconto"),2);
						$listino = $listino + round($listino / 100 * $rs->Fields("sconto"),2);
						break;
						
					case 3:
						$spedizione = $spedizione + round($spedizione / 100 * $rs->Fields("sconto"),2);
						break;
				}
					$rs->Close();
			} else {
				# FORNITORE
				if($fornitore!="") {
					$qry = "SELECT s.sconto as sconto,s.tipo as tipo FROM sconti s WHERE s.dal <= NOW() AND s.al >= NOW() AND s.fornitore='$fornitore' AND s.fornitore!='';";
					$rs = $conn->Execute($qry);
					if($rs->RecordCount()>0) {
						switch($rs->Fields("tipo")) {
							case 0:
								$listino = $listino + round($listino / 100 * $rs->Fields("sconto"),2);
								break;
								
							case 1:
								$scontato = $scontato + round($scontato / 100 * $rs->Fields("sconto"),2);
								break;
								
							case 2:
								$scontato = $scontato + round($scontato / 100 * $rs->Fields("sconto"),2);
								$listino = $listino + round($listino / 100 * $rs->Fields("sconto"),2);
								break;
								
							case 3:
								$spedizione = $spedizione + round($spedizione / 100 * $rs->Fields("sconto"),2);
								break;
						}
							$rs->Close();
					}	
				}
			}
		}
		$prezzi = Array($listino,$scontato,$spedizione);
		return $prezzi;
	}
}

class listCat  {
	var $cid;
	var $result;

	function listCat($cid)  {
		global $conn;
		$qry = "SELECT cid,titolo,hidden FROM categorie WHERE idfather=$cid AND attivo='y' ORDER BY ordine;";
		$rs = $conn->Execute($qry);
		if($rs)
		$this->result = $rs;
		else
		$this->result = NULL;
		$this->cid = $cid;
	}

	function show($cid1)  {
		global $conn,$order,$min,$max,$page;
		/*$content = '<div>';
		while(!$this->result->EOF)  {
			$qry = "SELECT COUNT(idarticolo) as num FROM articoli_new WHERE (cid=".$this->result->Fields("cid")." OR
		idarticolo IN (SELECT idarticolo FROM categorie_correlate WHERE cid=".$this->result->Fields("cid").")) AND attivo='y';";
			//$rs = $conn->Execute($qry);
			//$num = $rs->Fields("num");
			//$rs->Close();
			switch($cid1) {
				case 2:
					//piscine
					$folder = "piscine";
					break;

				case 3:
					//giardino
					$folder = "giardino";
					break;
			}
			$newCat = new category($this->result->Fields("cid"));
			$num = $newCat->getNumArticoli();
			$search = Array(' ','/','"');
			$content .= '<div class="box-arrow-cat"></div>
			<div class="box-titolo-cat"><a class=plain href="/'.str_replace($search,"-",$this->result->Fields("hidden")).'/">'.$this->result->Fields("titolo").' ('.$num.')</a></div>
			<div class="chiudi"></div>';
			$this->result->MoveNext();
		}
		$content .= "</div>\n";*/
		$content .= '<div id="listarticoli" class="plain">'.listArticoli::getThumb($this->cid,$order,$min,$max,$page).'</div>';
		return $content;
	}
}

//classe di gestione lista elementi
class listArticoli extends search  {
	var $cid;
	var $order;
	var $class;
	var $lang;

	function listArticoli($cid,$class,$lang,$order="ordine ASC")  {
		global $conn,$min,$max,$num_per_page;
		if (!isset($min))
		$min = 0;
		if (!isset($max))
		$max = $num_per_page;
		if($order=="")
		$order="ordine ASC";
		$qry = "SELECT idarticolo,cid,titolo1,image,image_tmb,promozione,vetrina,import,prezzo1,prezzo2,descrizione,hidden,disp,fornitore FROM articoli_new WHERE (cid=$cid OR
		idarticolo IN (SELECT idarticolo FROM categorie_correlate WHERE cid=$cid)) AND attivo='y' AND giardino=0 ORDER BY vetrina ASC,$order LIMIT $min,$max";
		$qry_tot = "SELECT idarticolo FROM articoli_new WHERE (cid=$cid OR
		idarticolo IN (SELECT idarticolo FROM categorie_correlate WHERE cid=$cid)) AND attivo='y' AND giardino=0;";
		//die("$qry<br>$qry_tot");
		$this->result = $conn->Execute($qry);
		$this->result_tot = $conn->Execute($qry_tot);
		$this->class = $class;
		$this->cid = $cid;
		$this->order = $order;
		$this->lang = $lang;
	}
	function show($min,$max,$page,$op)   {
		global $num_per_page,$lang,$cid1,$cid2,$cid3,$conn;
		$vetrina = false;
		switch($lang)  {
			case "ita":
				$prezzo1 = "Prezzo IVA inc. ";
				$prezzo2 = "Scontato";
				$compralo1 = "/images/compralo.gif";
		  break;

			case "eng":
				$prezzo1 = "Price";
				$prezzo2 = "Our price";
				$compralo1 = "/images-eng/compralo.gif";
		  break;
		}
		if ($page == "")
		$page = 1;
		$num_tot = $this->result_tot->RecordCount();
		if($num_tot > 0)  {
			$content = $this->makePages($min,$max,$page,$num_tot,"up",$op);
			if($this->order=="titolo1 ASC")
			$orderby1 = "titolo1 DESC";
			else
			$orderby1 = "titolo1 ASC";
			if($this->order=="prezzo2 ASC")
			$orderby2 = "prezzo2 DESC";
			else
			$orderby2 = "prezzo2 ASC";
			/*
			$qry = "SELECT id,nome FROM attributi_categorie WHERE cid=".$this->cid.";";
			$rs = esegui_queryRs($qry);
			if($rs->RecordCount() > 0) {
				$content .= '<div class="box-filtri-ricerca">
								<div style="width:100%; text-align:center; padding:5px;">FILTRI PER RICERCA</div>
				</div>';
				while(!$rs->EOF) {
					$content .= '<div>'.$rs->Fields("nome").'&nbsp;<select name="filtro-'.$rs->Fields("id").'" name="filtro-'.$rs->Fields("id").'">';
					$qry = "SELECT DISTINCT va.idvalore as idvalore,va.valore as valore FROM 
					((valore_attributo va LEFT JOIN attributi_categorie ac ON va.idattributo=ac.idattributo) 
					LEFT JOIN articolo_attributo a ON a.idvalore=va.idvalore) WHERE ac.idattributo=".$rs->Fields("id")." ORDER BY valore;";
					$rs2 = esegui_queryRs($qry);
					if($rs2->RecordCount()>0) {
						while(!$rs2->EOF) {
							$content .= '<option value="'.$rs2->Fields("valore").'">'.$rs2->Fields("valore").'</option>';
							$rs2->MoveNext();
						}
						$rs2->Close();
					}
					$content .= '</select></div>';
					$rs->MoveNext();
				}
				$rs->Close();
			}
			*/
			$content .= '<div class="spazio20"></div>
			<div class="box-filtri">
							<div><a class="plain" href="javascript:;" onClick="ordinaArticoli('.$this->cid.','.$min.','.$max.','.$page.',\''.$orderby1.'\')">Ordina per titolo</a></div>
							<div><a class="plain" href="javascript:;" onClick="ordinaArticoli('.$this->cid.','.$min.','.$max.','.$page.',\''.$orderby2.'\')">Ordina per prezzo</a></div>
			</div>
			<div class="spazio20"></div>';
			//stampo gli articoli
			$content .= '<div class="content-articoli">';
			$i = 1;
			$c = 1;
			$result = $this->result;
			while(!$result->EOF)  {
				switch($result->Fields("disp"))  {
				case "-1":
					$strdisp = '<br>  <span style="color:red;"><b>Articolo al momento esaurito!</b></span>';
					break;
	
				case "0":
					$strdisp = '<br>  <span style="color:red;"><b>Disponibilit&agrave; dell\'articolo da verificare.</b></span>';
					break;
	
				case "1":
					$strdisp = '';
					break;
			    }
				$permalink = fromTitToUrl($result->Fields("hidden"));
				if($result->Fields("codice")!="")
				$codice = '<br><b>COD. '.$result->Fields("codice").'</b>';
				else
				$codice = "";
				if($result->Fields("import")==1)
				$folder = "/immagini-piscine";
				else
				$folder = "/gestione/imgs_prodotti/".$result->Fields("idarticolo");
				if($result->Fields("image")!="")
				$image_tmb = "<a class=plain href=\"/$permalink/".$result->Fields("idarticolo")."\" title=\"".$result->Fields("titolo1")."\"><img width=80 src=\"$folder/".str_replace(" ","_",$result->Fields("image"))."\" border=0 alt=\"".$result->Fields("titolo1")."\"></a>";
				else
				$image_tmb = "&nbsp;";
				list($listino,$scontato,$spedizione) = articoli::getPrezzo($result->Fields("idarticolo"),$result->Fields("cid"),$result->Fields("prezzo1"),$result->Fields("prezzo2"),10,$result->Fields("fornitore"));
				if($result->Fields("prezzo2") != "0" && $result->Fields("promozione") == "y") {
			  $prezzo = '<span class="prezzo_elenco">'.number_format($scontato,2,",",".").' &euro;</span>';
			  $compralo = "&nbsp;&nbsp;<a href=\"/$permalink/".$result->Fields("idarticolo")."\" title=\"".$result->Fields("titolo1")."\"><img src=\"".$compralo1."\" border=0></a>";
				}	else  {
			  $prezzo = '<span class="prezzo_elenco">'.number_format($listino,2,",",".").' &euro;</span>';
			  $prezzosc = "&nbsp;";
			  $compralo = "&nbsp;";
				}
			if($result->Fields("vetrina")=="y") {
		 		if(!$vetrina) {
		 			$vetrina = true;
		 			$content .= '<div class="tit02" style="width:100%">In vetrina</div>';
		 		}
		 		$style = 'style="background-color:#E6CCFF;border-bottom:1px solid #FFFFFF"';
		 	} elseif($c == 1) {
			  $style = 'style="background-color:#FFFFFF"';
		 	} elseif($c == 2) {
		 		$style = 'style="background-color:#F6F7F4"';
		 	}
				//die(mb_detect_encoding($articolo->desc));
			 $arr_news = explode(" ",strip_tags($result->Fields("descrizione")));
			 if(count($arr_news)>10) {
			 	$strillo = '';
			 	for($y=0;$y<=10;$y++) {
			 		if($y>0) $strillo.=' ';
			 		$strillo .= $arr_news[$y];
			 	}
			 	$strillo .= "...";
			 } else
			 $strillo = $result->Fields("descrizione");

			 if (!isset($_GET['tab'])) {
				$content .= '<div class="box-image-articoli" '/*.$style*/.'>'.$image_tmb.' '.$codice.'</div>
							 <div class="box-titolo-articoli" '.$style.'>
								<a class=plain href="/'.$permalink.'/'.$result->Fields("idarticolo").'">'.htmlentities($result->Fields("titolo1")).'</a><br>
								'.($result->Fields("titolo2")!="" ? htmlentities($result->Fields("titolo2")).'<br>' : '').'
								'.htmlentities($strillo).'<br>
								<a href="/'.$permalink.'/'.$result->Fields("idarticolo").'" title="'.$result->Fields("titolo1").'" class="dettProd">Caratteristiche &gt;'./*'<img style="margin-top:10px" src="/images/apriScheda.jpg" border=0>'.*/'</a>
							 	<a href="/'.$permalink.'/'.$result->Fields("idarticolo").'#form" title="'.$result->Fields("titolo1").'" class="richiediInfoProd">Richiedi info</a>
							 	'.$strdisp.'
							 </div>
							 <div class="box-prezzo-articoli" '.$style.'>'.$prezzo.'<br>';
							 
				if ($result->Fields("disp")=="-1") {
					$content .= '<a href="/'.$permalink.'/'.$result->Fields("idarticolo").'#form"><img alt="'.$altimage.'" src="/images/btnPrev.jpg" border=0></a>';
				} else {
					$content .= '<a href="javascript:;" onClick="addArticolo(\''.$result->Fields("idarticolo").'\')"><img src="/images/compralo.gif" border=0></a>';
				}
					
				$content .= '	<br><p class="btnFB"><fb:like layout="button_count" href="http://www.bsvillage.com/'.$permalink.'/'.$result->Fields("idarticolo").'"></fb:like></p>
							 </div>'; 	
			 } else {
				$bgcolor = ($c%2==0)?"style=\"background:#F6F7F4;":"style=\"";
				$content .= '<table width="660" border="0" cellspacing="0" cellpadding="0" style="margin-bottom:5px">
					  			<tr>
									<td width="80">'.$image_tmb.' '.$codice.'</td>
									<td width="10"></td>
									<td width="420" valign="top" '.$bgcolor.'font-size:11px;">
										<a class=plain href="/'.$permalink.'/'.$result->Fields("idarticolo").'" style="color:#7584A1;font-weight:bold;text-decoration: none;">'.htmlentities($result->Fields("titolo1")).'</a>
										<br>
										'.($result->Fields("titolo2")!="" ? htmlentities($result->Fields("titolo2")).'<br>' : '').'
										'.htmlentities($strillo).'<br>
										<a href="/'.$permalink.'/'.$result->Fields("idarticolo").'" title="'.$result->Fields("titolo1").'" class="dettProd">Caratteristiche &gt;'./*'<img style="margin-top:10px" src="/images/apriScheda.jpg" border=0>'.*/'</a>
										<a href="/'.$permalink.'/'.$result->Fields("idarticolo").'#form" title="'.$result->Fields("titolo1").'" class="richiediInfoProd">Richiedi info</a>
										'.$strdisp.'
									</td>
									<td width="150" '.$bgcolor.'color:#666666;font-size: 15px;font-weight: bold;">
										'.$prezzo.'<br>
							 			<a href="javascript:;" onClick="addArticolo(\''.$result->Fields("idarticolo").'\')"><img src="/images/compralo.gif" border=0></a>
									</td>
					  			</tr>
							 </table>';
			 }
			 

		  if($c > 1)
		  $c = 1;
		  elseif($c == 1)
		  $c++;
		  $result->MoveNext();
			}
			$content .= '</div>
			<div class="spazio20"></div>';
			$content .= $this->makePages($min,$max,$page,$num_tot,"down",$op);
		} else {
			$content = "";
		}
		return $content;
	}

	function getThumb($cid,$order,$min,$max,$page,$op,$filtro=Array())  {
		global $conn,$lang,$cid1,$cid2,$cid3;
		$vetrina = false;
		$list_cid = category::getChild($cid,$cid);
		if($page=="") $page=1;
		if($order=="")
		  $order = "idarticolo";
		if(count($filtro) > 0) {
			$sql_filtro = "SELECT ac.idarticolo as idarticolo,COUNT(ac.idarticolo) as num FROM articolo_attributo ac WHERE ";
			$i = 1;
			foreach ($filtro as $id=>$idvalore) {
				if($i>1) $sql_filtro .= " OR "; 
				$sql_filtro .= '(ac.idattributo='.$id.' AND ac.idvalore='.$idvalore.')'; 
				$i++;
			}
			$sql_filtro .= " GROUP BY ac.idarticolo";
			$qry = "SELECT DISTINCT a.idarticolo as idarticolo,a.cid as cid,a.titolo1 as titolo1,a.image as image,a.image_tmb as image_tmb,a.promozione as promozione,a.vetrina as vetrina,a.import as import,a.prezzo1 as prezzo1,a.prezzo2 as prezzo2,a.descrizione as descrizione,a.hidden,a.disp as disp,a.fornitore as fornitore,a.vetrinacat as vetrinacat 
			FROM ((articoli_new a INNER JOIN categorie ON a.cid=categorie.cid) LEFT OUTER JOIN attributi_categorie_articoli ac ON a.idarticolo=ac.idarticolo) 
			WHERE a.lang='$lang' AND a.attivo='y' AND a.idarticolo IN (SELECT idarticolo FROM ($sql_filtro) as t1 WHERE num=".count($filtro).")  AND 
			(categorie.cid IN ($list_cid) OR a.idarticolo IN 
			(SELECT ca.idarticolo as idarticolo FROM categorie_correlate ca WHERE ca.cid IN ($list_cid)))  
			 ORDER BY a.vetrinacat DESC,a.$order LIMIT $min,$max;";
			$qry_tot = "SELECT COUNT(DISTINCT a.idarticolo) as num  
			FROM ((articoli_new a INNER JOIN categorie ON a.cid=categorie.cid) LEFT OUTER JOIN attributi_categorie_articoli ac ON a.idarticolo=ac.idarticolo) 
			WHERE a.lang='$lang' AND a.attivo='y' AND a.idarticolo IN (SELECT idarticolo FROM ($sql_filtro) as t1 WHERE num=".count($filtro).")  AND 
			(categorie.cid IN ($list_cid) OR a.idarticolo IN 
			(SELECT ca.idarticolo as idarticolo FROM categorie_correlate ca WHERE ca.cid IN ($list_cid)));";
			//die($qry."<br>".$qry_tot);
		} else {
			$qry = "SELECT articoli_new.idarticolo as idarticolo,articoli_new.cid as cid,articoli_new.titolo1 as titolo1,articoli_new.image as image,articoli_new.image_tmb as image_tmb,articoli_new.promozione as promozione,articoli_new.vetrina as vetrina,articoli_new.import as import,articoli_new.prezzo1 as prezzo1,articoli_new.prezzo2 as prezzo2,articoli_new.descrizione as descrizione,articoli_new.hidden,articoli_new.disp,articoli_new.fornitore,articoli_new.vetrinacat as vetrinacat FROM articoli_new INNER JOIN categorie ON articoli_new.cid=categorie.cid WHERE articoli_new.lang='$lang' AND articoli_new.giardino=0 AND articoli_new.attivo='y' AND (categorie.cid IN ($list_cid) OR idarticolo IN (SELECT idarticolo FROM categorie_correlate WHERE cid IN
		($list_cid))) ORDER BY articoli_new.vetrinacat DESC,articoli_new.$order LIMIT $min,$max;";
			$qry_tot = "SELECT COUNT(articoli_new.idarticolo) as num FROM articoli_new INNER JOIN categorie ON articoli_new.cid=categorie.cid WHERE articoli_new.lang='$lang' AND articoli_new.giardino=0 AND articoli_new.attivo='y' AND (categorie.cid IN ($list_cid) OR idarticolo IN (SELECT idarticolo FROM categorie_correlate WHERE cid IN
		($list_cid)));";
		}
		//die("$qry<br>$qry_tot");
		$rs = $conn->Execute($qry);
		$rs_tot = $conn->Execute($qry_tot);
		$num_tot = $rs_tot->Fields("num");
		$ordina = '';
		$paginator = listArticoli::makePagesThumb($min,$max,$page,$num_tot,$order);
		if($rs)  {
			$content = $paginator;
			$i = 1;
			if($order=="titolo1 ASC")
			$orderby1 = "titolo1 DESC";
			else
			$orderby1 = "titolo1 ASC";
			if($order=="prezzo2 ASC")
			$orderby2 = "prezzo2 DESC";
			else
			$orderby2 = "prezzo2 ASC";
			/*
			$qry = "SELECT DISTINCT at.idattributo as idattributo,at.nome FROM ((
			attributi at INNER JOIN articolo_attributo aa ON at.idattributo=aa.idattributo) 
			INNER JOIN articoli_new a ON aa.idarticolo=a.idarticolo) WHERE a.cid IN ($list_cid);";
			$rs3 = esegui_queryRs($qry);
			$num = $rs3->RecordCount();
			switch($num) {
				case 2:
					$width = "50%";
					break;
					
				case 3:
					$width = "33%";
					break;
					
				case 4:
					$width = "25%";
					break;
				case 5:
					$width = "20%";
					break;
			}
			
			if($num > 0) {
				$ordina .= '<div class="box-filtri-ricerca">
								<div style="position:relative:float:left;width:100%; text-align:center; padding:5px;">RICERCA AVANZATA</div>';
				while(!$rs3->EOF) {
					$ordina .= '<div class="box-ricerca-varianti">
					<p style="font-weight:bolder">'.$rs3->Fields("nome").'</p>';
					$right .= '<select name="filtro-'.$rs3->Fields("idattributo").'" name="filtro-'.$rs3->Fields("idattributo").'" onChange="ordinaThumbs(\''.$cid.'\',\'\');">';
					$qry = "SELECT DISTINCT va.idvalore as idvalore,va.valore as valore FROM 
					valore_attributo va INNER JOIN attributi_categorie ac ON va.idattributo=ac.idattributo
					 WHERE ac.idattributo=".$rs3->Fields("idattributo")." AND va.valore LIKE '%[%' ORDER BY idvalore;";
					$rs2 = esegui_queryRs($qry);
					if($rs2->RecordCount()>0) {
						while(!$rs2->EOF) {
							if($filtro[$rs3->Fields("idattributo")]==$rs2->Fields("idvalore")) {
								$sel = 'id="filtro-'.$rs3->Fields("idattributo").'" title="'.$rs2->Fields("idvalore").'" style="background-color:#C6DBFF" ';
								$cross = 'x';
							} else {
								$sel = "";
								$cross = '';
							}
							$ordina .= '<p><a '.$sel.' class="plain" href="javascript:;" onClick="ordinaThumbs(\''.$cid.'\',\'\','.$rs3->Fields("idattributo").',\''.$rs2->Fields("idvalore").'\')" rel="nofollow">'.str_replace(array('[',']'),"",$rs2->Fields("valore")).'</a></p>';
							$rs2->MoveNext();
						}
						$rs2->Close();
					} else {
						$qry = "SELECT DISTINCT va.idvalore as idvalore,va.valore as valore FROM 
						(valore_attributo va INNER JOIN attributi_categorie ac ON va.idattributo=ac.idattributo) INNER JOIN 
						articolo_attributo aa ON aa.idvalore=va.idvalore
						 WHERE ac.idattributo=".$rs3->Fields("idattributo")." ORDER BY cast(valore as UNSIGNED);";
						$rs2 = esegui_queryRs($qry);
						if($rs2->RecordCount()>0) {
							while(!$rs2->EOF) {
								if($filtro[$rs3->Fields("idattributo")]==$rs2->Fields("idvalore")) {
									$sel = 'id="filtro-'.$rs3->Fields("idattributo").'" title="'.$rs2->Fields("idvalore").'" style="background-color:#C6DBFF" ';
									$cross = 'x';
								} else {
									$sel = "";
									$cross = '';
								}
									$ordina .= '<p><a '.$sel.'class="plain" href="javascript:;" onClick="ordinaThumbs(\''.$cid.'\',\'\','.$rs3->Fields("idattributo").',\''.$rs2->Fields("idvalore").'\')" rel="nofollow">'.str_replace(array('[',']'),"",$rs2->Fields("valore")).'</a></p>';
									$rs2->MoveNext();
							}
							$rs2->Close();
						}
					}
					$ordina .= '</div>';
					$rs3->MoveNext();
				}
				$ordina .= '<div class="chiudi"></div>
				<div style="position:relative:float:left;width:100%; text-align:center; padding:5px;"><a class="plain" href="javascript:;" onClick="pulisciFiltri('.$cid.')">AZZERA FILTRI</a></div>
				</div>';
				$rs3->Close();
			}
			*/
			$ordina .= '<div class="box-filtri">
							<div><a class="plain" href="javascript:;" onClick="ordinaArticoli('.$cid.','.$min.','.$max.','.$page.',\''.$orderby1.'\')">Ordina per titolo</a></div>
							<div><a class="plain" href="javascript:;" onClick="ordinaArticoli('.$cid.','.$min.','.$max.','.$page.',\''.$orderby2.'\')">Ordina per prezzo</a></div>
			</div>';
			$content .= '<div class="spazio20"></div>'.$ordina.'<div class="spazio20"></div>';
		 while(!$rs->EOF) {
		 	switch($cid1) {
		 		case 2:
		 			//piscine
		 			$folder2 = "piscine";
		 			break;
		 				
		 		case 3:
		 			//giardino
		 			$folder2 = "giardino";
		 			break;
		 	}
		 	switch($rs->Fields("disp"))  {
				case "-1":
					$strdisp = '<br>  <span style="color:red;"><b>Articolo al momento esaurito!</b></span>';
					break;
	
				case "0":
					$strdisp = '<br>  <span style="color:red;"><b>Disponibilit&agrave; dell\'articolo da verificare.</b></span>';
					break;
	
				case "1":
					$strdisp = '';
					break;
			    }
		 	$permalink = fromTitToUrl($rs->Fields("hidden"));
		 	if($rs->Fields("codice")!="")
		 	$codice = '<br><b>COD. '.$rs->Fields("codice").'</b>';
		 	else
		 	$codice = "";
		 	if($rs->Fields("import")==1)
		 	$folder = "/immagini-piscine";
		 	else
		 	$folder = "/gestione/imgs_prodotti/".$rs->Fields("idarticolo");
		 	if($rs->Fields("image")!="")
		 	$image_tmb = "<a href=\"/$permalink/".$rs->Fields("idarticolo")."\" title=\"".$rs->Fields("titolo1")."\"><img width=80 src=\"$folder/".str_replace(" ","_",$rs->Fields("image"))."\" border=0 alt=\"".$rs->Fields("titolo1")."\"></a>";
		 	else
		 	$image_tmb = "&nbsp;";
		 	list($listino,$scontato,$spedizione) = articoli::getPrezzo($rs->Fields("idarticolo"),$rs->Fields("cid"),$rs->Fields("prezzo1"),$rs->Fields("prezzo2"),10,$rs->Fields("fornitore"));
		 	if($rs->Fields("prezzo2") != "0" && $rs->Fields("promozione") == "y") {
			  $prezzo = '<span class="prezzo_elenco">'.number_format($scontato,2,",",".").' &euro;</span>';
			  $prezzosc = $prezzo2.': '.number_format($scontato,2,",",".").' &euro;';
		 	}	else  {
			  $prezzo = '<span class="prezzo_elenco">'.number_format($listino,2,",",".").' &euro;</span>';
			  $prezzosc = "&nbsp;";
		 	}
		 	$titolo = '<a class=plain href="/'.$permalink.'/'.$rs->Fields("idarticolo").'" title="'.$rs->Fields("titolo1").'">'.$rs->Fields("titolo1").'</a>';
		 	if($rs->Fields("vetrinacat") == 1) {
		 		if(!$vetrina) {
		 			$vetrina = true;
		 			$content .= '<div class="tit02" style="width:100%">In vetrina</div>';
		 		}
		 		$style = 'style="background-color:#E6CCFF;border-bottom:1px solid #FFFFFF"';
		 	} elseif($i % 2 == 1) {
			  //$content .= "<tr bgcolor=#FFFFFF>";
			  $style = 'style="background-color:#FFFFFF"';
		 	} else {
		 		//$content .= "<tr bgcolor=#F6F7F4>";
		 		$style = 'style="background-color:#F6F7F4"';
		 	}
		 	$arr_news = explode(" ",strip_tags($rs->Fields("descrizione")));
		 	if(count($arr_news)>10) {
		 		$strillo = '';
		 		for($y=0;$y<=10;$y++) {
		 			if($y>0) $strillo.=' ';
		 			$strillo .= $arr_news[$y];
		 		}
		 		$strillo .= "...";
		 	} else
		 	$strillo = $rs->Fields("descrizione");


			 if (!isset($_GET['tab'])) {
					$content .= '<div class="box-image-articoli" '/*.$style*/.'>'.$image_tmb.' '.$codice.'</div>
								 <div class="box-titolo-articoli" '.$style.'>
								 <a class=plain href="/'.$permalink.'/'.$rs->Fields("idarticolo").'">'.htmlentities($rs->Fields("titolo1")).'</a><br>
					'.($rs->Fields("titolo2")!="" ? htmlentities($rs->Fields("titolo2")).'<br>' : '').'
					'.htmlentities($strillo).'<br>
					<a href="/'.$permalink.'/'.$rs->Fields("idarticolo").'" title="'.$rs->Fields("titolo1").'" class="dettProd">Caratteristiche &gt;'./*'<img style="margin-top:10px" src="/images/apriScheda.jpg" border=0>'.*/'</a>'.
					'<a href="/'.$permalink.'/'.$rs->Fields("idarticolo").'#form" title="'.$rs->Fields("titolo1").'" class="richiediInfoProd">Richiedi info</a>
					'.$strdisp.'
								 </div>
								 <div class="box-prezzo-articoli" '.$style.'>'.$prezzo.'<br>
					<a href="javascript:;" onClick="addArticolo(\''.$rs->Fields("idarticolo").'\')"><img src="/images/compralo.gif" border=0></a><br><p class="btnFB"><fb:like layout="button_count" href="http://www.bsvillage.com/'.$permalink.'/'.$rs->Fields("idarticolo").'"></fb:like><p></div>';  	
			 } else {
				$bgcolor = ($i%2==0)?"style=\"background:#F6F7F4;":"style=\"";
				$content .= '<table width="660" border="0" cellspacing="0" cellpadding="0" style="margin-bottom:5px">
					  			<tr>
									<td width="80">'.$image_tmb.' '.$codice.'</td>
									<td width="10"></td>
									<td width="420" valign="top" '.$bgcolor.'font-size:11px;">
										<a class=plain href="/'.$permalink.'/'.$rs->Fields("idarticolo").'" style="color:#7584A1;font-weight:bold;text-decoration: none;">'.htmlentities($rs->Fields("titolo1")).'</a>
										<br>
										'.($rs->Fields("titolo2")!="" ? htmlentities($rs->Fields("titolo2")).'<br>' : '').'
										'.htmlentities($strillo).'<br>
										<a href="/'.$permalink.'/'.$rs->Fields("idarticolo").'" title="'.$rs->Fields("titolo1").'" class="dettProd">Caratteristiche &gt;'./*'<img style="margin-top:10px" src="/images/apriScheda.jpg" border=0>'.*/'</a>'.
										'<a href="/'.$permalink.'/'.$rs->Fields("idarticolo").'#form" title="'.$rs->Fields("titolo1").'" class="richiediInfoProd">Richiedi info</a>
										'.$strdisp.'
									</td>
									<td width="150" '.$bgcolor.'color:#666666;font-size: 15px;font-weight: bold;">
										'.$prezzo.'<br>
							 			<a href="javascript:;" onClick="addArticolo(\''.$rs->Fields("idarticolo").'\')"><img src="/images/compralo.gif" border=0></a>
									</td>
					  			</tr>
							 </table>';
			 }
			
			
			
		 	$i++;
		  $rs->MoveNext();
		 }
		 $content .= '<div class="spazio20"></div>'.$paginator.'<div class="spazio20"></div>';
		 $rs->Close();
		} else
		$content = "&nbsp;";
		return $content;
	}
	
	function makePagesThumb($min,$max,$page,$num_tot,$order)  {
		global $num_per_page,$cid1,$cid2,$cid3,$num_page_show;
		$ricerca = "Ricerca";
		$trovati = "Risultati trovati";
		$di = "di";
		if($cid1=="" && $op!="search_web") {
	  		list($cid3,$cid2,$cid1) = explode("-",category::getParent($this->cid,$this->cid));
	  		$op = "";
		}
		if($cid2=="" && $cid3=="")
		$folder2 = "ita";
		$num_pages = ($num_tot/$num_per_page) + 1;
		$resto =  $num_tot%$num_per_page;
		list($num_pages) = explode(".",$num_pages);
		if ($resto==0)
		$num_pages--;
		if ($num_pages>1) {
		$content = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\" class=plain>
				<tr>
                    <td width=\"140\" class=\"plain\">$trovati: $num_tot</td>
                    <td width=\"200\" class=\"plain\"><div align=\"center\">pag $page $di $num_pages </div></td>";
		$resto_page = $num_pages % $num_page_show;
		$quoz_page = $num_pages / $num_page_show;
		$resto = $page % $num_page_show;
		//calcolo l'intervallo delle pagine da visualizzare
		if($num_pages > $num_page_show && $page > $num_page_show)  {
			$start = $page - $resto + 1;
			$end = $start + $num_page_show - 1;
			if($end > $num_pages)
			$end = $num_pages;
		} elseif($page <= $num_page_show)  {
			$start = 1;
			if($num_pages >= $num_page_show)
			$end = $num_page_show;
			else
			$end = $num_pages;
		}
		$content .= "<td class=\"plain\"><div align=\"center\">";
		
		//pagine precedenti
		if(($resto_page > 0 || $quoz_page > 1)  && $num_pages > $num_page_show && $page > $num_page_show) {
			if($page > $num_page_show)  {
				$page1 = $page - $resto;
				$min1 = ($page1 - 1) * $num_per_page;
			} else {
				$page1 = $num_page_show;
				$min1 = 90;
			}
			$content .= "<a href=\"/webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min1&max=$num_per_page&page=$page1&order=$order\" class=\"plain\">&lt;&lt;</a>&nbsp;";
		}
		/**/
		if(($resto_page > 0 || $quoz_page > 1) && $page > 1) {
		if($page > $num_page_show)  {
				$page1 = $page - 1;
				$min1 = ($page1 - 1) * $num_per_page;
			} else {
				$page1 = $page-1;
				$min1 = $min-$num_per_page;
			}
			$content .= "<a href=\"/webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min1&max=$num_per_page&page=$page1&order=$order\" class=\"plain\">&lt;</a>&nbsp;";
		}
		/**/
		if ($start<$end) {
			for ($i=$start;$i<=$end;$i++)  {
				if ($page!=$i)  {
					$max1 = $i*$num_per_page;
					$min1 = $max1 - $num_per_page;
					$content .= "<a href=\"/webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min1&max=$num_per_page&page=$i&order=$order\" class=\"plain a-pag\">$i</a>";
					$content .= "  ";
				}  else
				$content .= "  <span class=\"pag-sel\">$i</span>  ";
			}
		}
		//pagine successive
		//echo ($resto_page > 0) ."-". ($quoz_page > 1) ."-". ($num_pages > $num_per_page) ."-". ($num_pages != $end);
		//echo $resto_page ."-". $quoz_page ."-".$num_pages ."-".$num_per_page."-".$num_pages ."-".$end;
		/**/
		if(($resto_page > 0 || $quoz_page > 1)  && $num_pages != $page) {
			if($page <= $num_pages)  {
				$page2 = $page + 1;
				$min2 = $page * $num_per_page;
			} else {
				$min2 = $min1 + $num_per_page;
				$page2 = $i;
			}
			$content .= "&nbsp;<a href=\"/webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min2&max=$num_per_page&page=$page2&order=$order\" class=\"plain\">&gt;</a>";
		}
		/**/
		if(($resto_page > 0 || $quoz_page > 1)  && $num_pages > $num_page_show && $num_pages != $end) {
			if($page <= $num_per_page)  {
				$page2 = $num_page_show + 1;
				$min2 = $num_per_page * $num_page_show;
			} else {
				$min2 = $min1 + $num_per_page;
				$page2 = $i;
			}
			$content .= "&nbsp;<a href=\"/webproduct.php?cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min2&max=$num_per_page&page=$page2&order=$order\" class=\"plain\">&gt;&gt;</a>";
		}
		
		$content .= "</div></td></tr>
		</table>";
		}
		return $content;
	}
}

class topElement  {
	var $result;

	function topElement($id_user)  {
		$qry = "SELECT idelement FROM element WHERE id_user='$id_user' AND in_evidenza='y' ORDER BY rand() LIMIT 0,1;";
		$this->result = mysql_query($qry);
	}

	function getElement()  {
		list($idelement) = mysql_fetch_row($this->result);
		$newElement = new element($idelement);
		return $newElement;
	}
}

//classe di gestione ricerca articoli
class search {
	var $search;
	var $result;
	var $result_next;
	var $result_tot;
	var $lang;

	function search($search)  {
		global $conn,$min,$max,$num_per_page,$lang;
		if (!isset($min))
		$min = 0;
		if (!isset($max))
		$max = $num_per_page;
		$this->search = $search;
		if(strlen($search)>3)  {
			$qry = "SELECT idarticolo, MATCH(codice,titolo1,titolo2,descrizione) AGAINST('$search' IN BOOLEAN MODE) AS attinenza FROM articoli_new WHERE MATCH(codice,titolo1,titolo2,descrizione) AGAINST('$search' IN BOOLEAN MODE) AND attivo='y' AND giardino=0 AND cid!=521 ORDER BY attinenza desc LIMIT $min,$max";
			$qry_tot = "SELECT idarticolo, MATCH(codice,titolo1,titolo2,descrizione) AGAINST('$search' IN BOOLEAN MODE) AS attinenza FROM articoli_new WHERE MATCH(codice,titolo1,titolo2,descrizione) AGAINST('$search' IN BOOLEAN MODE) AND attivo='y' AND giardino=0 AND cid!=521;";
		} else {
			$qry = "SELECT idarticolo FROM articoli_new WHERE codice LIKE '%$search%' OR titolo1 LIKE '%$search%' OR titolo2 LIKE '%$search%' OR descrizione LIKE '%$search%' AND attivo='y' AND giardino=0 AND cid!=521 ORDER BY titolo1 LIMIT $min,$max";
			$qry_tot = "SELECT idarticolo FROM articoli_new WHERE codice LIKE '%$search%' OR titolo1 LIKE '%$search%' OR titolo2 LIKE '%$search%' OR descrizione LIKE '%$search%' AND attivo='y' AND giardino=0 AND cid!=521;";
		}
		//die($qry_tot);
		$this->result = $conn->Execute($qry);
		$this->result_tot = $conn->Execute($qry_tot);
		$this->lang = $lang;
	}

	function getSearch($min,$max,$page,$op)  {
		global $num_per_page,$cid1,$cid2,$cid3;
		if ($page == "")
		$page = 1;
		$num_tot = $this->result_tot->RecordCount();
		if($num_tot > 0)  {
			$cid_index = $cid1;
			$content = $this->makePages($min,$max,$page,$num_tot,"up",$op);
			//stampo gli articoli
			$content .= "<table width=100% class=$this->class cellpadding=0>";
			$i = 1;
			$c = 1;
			while(!$this->result->EOF)  {
				$articolo = new articoli($this->result->Fields("idarticolo"));
				$permalink = fromTitToUrl($articolo->hidden);
				$cat = new category($articolo->cid);
				$permalink_cat = fromTitToUrl($cat->hidden);
				list($cid3,$cid2,$cid1) = explode("-",category::getParent($cat->cid,$cat->cid));
				if($cid1 == "")  {
			  $cid1 = $cid2;
			  $cid2 = $cid3;
			  $cid3 = "";
				}
				if($articolo->import==1)
				$folder = "/immagini-piscine";
				else
				$folder = "/gestione/imgs_prodotti/$articolo->idarticolo";
				if($articolo->image!="")
				$image_tmb = "<a class=plain href=\"/$permalink/$articolo->idarticolo\"><img width=80 src=\"$folder/".str_replace(" ","_",$articolo->image)."\" border=0 alt=\"Apri dettaglio\"></a>";
				else
				$image_tmb = "&nbsp;";
				if($c == 1 && $i == 1) {
			  $content .= "<tr bgcolor=#FFFFFF>";
				} elseif($c == 2 && $i == 1) {
					$content .= "<tr bgcolor=#F6F7F4>";
				}
				$content .= "<td width=50%><table width=100% class=plain cellpadding=2><tr><td width=80>$image_tmb</td><td><a class=plain href=\"/$permalink/$articolo->idarticolo\">$articolo->titolo1</a><br>codice: $articolo->codice<br>
			Categoria: <a class=plain href=\"/$permalink_cat/\">$cat->titolo</a></td></tr></table></td>";
				if($i > 1) {
					$content .= "</tr>\n";
					$i = 1;
				} else
				$i++;
		  if($i > 1 && $c > 1)
		  $c = 1;
		  elseif($i > 1 && $c == 1)
		  $c++;
		  $this->result->MoveNext();
			}
			if($i == 2) {
				$content .= "<td>&nbsp;</td></tr>\n";
			}
			$cid1 = $cid_index;
			$cid2 = "";
			$cid3 = "";
			$content .= $this->makePages($min,$max,$page,$num_tot,"down",$op);
		} else {
			$content = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\" class=plain>
                <tr>
                 <td width=100% align=center>Nessun risultato trovato per questa ricerca.</td>
				</tr>
			</table>";
		}
		return $content;
	}

	function makePages($min,$max,$page,$num_tot,$where,$op)  {
		global $num_per_page,$cid1,$cid2,$cid3,$num_page_show;
		$num_page_show = 15;
		switch($this->lang)  {
			case "ita":
				$ricerca = "Ricerca";
				$trovati = "Risultati trovati";
				$di = "di";
				break;
					
			case "eng":
				$ricerca = "Search for";
				$trovati = "Results found";
				$di = "of";
				break;
		}
		if($cid1=="" && $op!="search_web") {
	  list($cid3,$cid2,$cid1) = explode("-",category::getParent($this->cid,$this->cid));
	  $op = "";
		}
		if($cid2=="" && $cid3=="")
		$folder2 = "ita";
		$num_pages = ($num_tot/$num_per_page) + 1;
		$resto =  $num_tot%$num_per_page;
		list($num_pages) = explode(".",$num_pages);
		if ($resto==0)
		$num_pages--;
		$content = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\" class=plain>";
		if($where == "up")
		$content .= "<tr>
                    	<td colspan=\"3\" class=\"plain\">$ricerca: $this->search</td>
                  		</tr>";
		$content .= "
                  <tr>
                    <td width=\"140\" class=\"plain\">$trovati: $num_tot</td>
                    <td width=\"200\" class=\"plain\"><div align=\"center\">pag $page $di $num_pages </div></td>";
		$resto_page = $num_pages % $num_page_show;
		$quoz_page = $num_pages / $num_page_show;
		$resto = $page % $num_page_show;
		//calcolo l'intervallo delle pagine da visualizzare
		if($num_pages > $num_page_show && $page > $num_page_show)  {
			$start = $page - $resto + 1;
			$end = $start + $num_page_show - 1;
			if($end > $num_pages)
			$end = $num_pages;
		} elseif($page <= $num_page_show)  {
			$start = 1;
			if($num_pages >= $num_page_show)
			$end = $num_page_show;
			else
			$end = $num_pages;
		}
		$content .= "<td class=\"plain\"><div align=\"center\">";
		if(($resto_page > 0 || $quoz_page > 1)  && $num_pages > $num_page_show && $page > $num_page_show) {
			//pagine precedenti
			if($page > $num_page_show)  {
				$page1 = $page - $resto;
				$min1 = ($page1 - 1) * $num_per_page;
			} else {
				$page1 = $num_page_show;
				$min1 = 90;
			}
			$content .= "<a href=\"/webproduct.php?op=$op&search=$this->search&cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min1&max=$num_per_page&page=$page1&order=$this->order\" class=\"plain\">&lt;&lt;</a>&nbsp;";
		}
		/**/
		if(($resto_page > 0 || $quoz_page > 1) && $page > 1) {
			if($page > $num_page_show)  {
				$page1 = $page - 1;
				$min1 = ($page1 - 1) * $num_per_page;
			} else {
				$page1 = $page-1;
				$min1 = $min-$num_per_page;
			}
			$content .= "<a href=\"/webproduct.php?op=$op&search=$this->search&cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min1&max=$num_per_page&page=$page1&order=$this->order\" class=\"plain\">&lt;</a>&nbsp;";
		}
		/**/
		
		if ($start<$end) {
			for ($i=$start;$i<=$end;$i++)  {
				if ($page!=$i)  {
					$max1 = $i*$num_per_page;
					$min1 = $max1 - $num_per_page;
					$content .= "<a href=\"/webproduct.php?op=$op&search=$this->search&cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min1&max=$num_per_page&page=$i&order=$this->order\" class=\"plain a-pag\">$i</a>";
					$content .= "  ";
				}  else
				$content .= "  <span class=\"pag-sel\">$i</span>  ";
			}
		}
		
		/**/
		if(($resto_page > 0 || $quoz_page > 1)  && $num_pages != $page) {
			if($page <= $num_pages)  {
				$page2 = $page + 1;
				$min2 = $page * $num_per_page;
			} else {
				$min2 = $min1 + $num_per_page;
				$page2 = $i;
			}
			$content .= "&nbsp;<a href=\"/webproduct.php?op=$op&search=$this->search&cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min2&max=$num_per_page&page=$page2&order=$this->order\" class=\"plain\">&gt;</a>";
		}
		/**/
		//pagine successive
		if(($resto_page > 0 || $quoz_page > 1)  && $num_pages > $num_page_show && $num_pages != $end) {
			if($page <= $num_page_show)  {
				$page2 = $num_page_show + 1;
				$min2 = $num_per_page * $num_page_show;
			} else {
				$min2 = $min1 + $num_per_page;
				$page2 = $i;
			}
			$content .= "&nbsp;<a href=\"/webproduct.php?op=$op&search=$this->search&cid1=$cid1&cid2=$cid2&cid3=$cid3&min=$min2&max=$num_per_page&page=$page2&order=$this->order\" class=\"plain\">&gt;&gt;</a>";
		}
		$content .= "</div></td></tr>
		</table>";
		return $content;
	}
}

class Variante {
	
	function listAttributi() {
	  $qry = "SELECT idattributo,nome FROM attributi ORDER BY idattributo;";
	  $rs = esegui_queryRs($qry);
	  if($rs->RecordCount()>0) {
		$result = '<table class="content" cellpadding="2" width="500">
						<tr>
						  <td class="error" colspan="3" align="center">ELENCO VARIANTI</td>
						</tr>';
		while(!$rs->EOF) {
		  $result .= '<tr>
		  				<td width="300">'.$rs->Fields("idattributo").':'.utf8_encode($rs->Fields("nome")).'</td>
		  				<td align="center"><a href="javascript:;" onClick="editVariante('.$rs->Fields("idattributo").');"><img src="imgs/ico_edit.gif" border="0"></a>&nbsp;&nbsp;<a href="javascript:;" onClick="delVariante('.$rs->Fields("idattributo").');"><img src="imgs/ico_delete.gif" border="0"></a>&nbsp;&nbsp;<a href="javascript:;" onClick="getValori('.$rs->Fields("idattributo").');"><img src="imgs/ico_ordini.gif" border="0" title="Valori Variante"></a></td>
		  			  </tr>';
		  $rs->MoveNext();
		}
		$result .= '</table>';
		$rs->Close();
	  } else
	  	  $result = '';
	  return $result;
	}
	
	function saveAttributo($nome,$cids) {
	  global $conn;
	  $nome = addslashes($nome);
	  $qry = "INSERT INTO attributi VALUES(NULL,'$nome');";
	  //die($qry);
	  $error = esegui_queryInsert($qry);
	  if($error>0) {
	  	foreach($cids as $cid) {
	  		$conn->Execute("INSERT INTO attributi_categorie VALUES($error,$cid)");
	  	}
	    return $error;	
	  }
	  else
	    return 0;
	}
	
	function getAttributo($idattributo) {
		global $conn;
		$qry = "SELECT * FROM attributi WHERE idattributo=$idattributo;";
		$rs = $conn->Execute($qry);
		$varianti = Variante::getCategorie($rs->Fields("idattributo"));
		$json = '{"idattributo":'.$rs->Fields("idattributo").',"nome":'.json_encode($rs->Fields("nome")).',"varianti":'.Variante::getCategorieFull().',"cids":'.($varianti != "" ? $varianti : '[]').'}';
		return $json;	
	}
	
	function getIdAttributo($idvalore) {
		global $conn;
		$qry = "SELECT idattributo FROM valore_attributo WHERE idvalore=$idvalore;";
		$rs = esegui_queryRs($qry);
		return $rs->Fields("idattributo");	
	}
	
	function getNomeAttributo($idattributo) {
		global $conn;
		$qry = "SELECT nome FROM attributi WHERE idattributo=$idattributo;";
		$arr = esegui_query($qry);
		return $arr[0]['nome'];	
	}
	
	function updAttributo($idattributo,$nome,$cids) {
	  global $conn;
	  $nome = addslashes($nome);
	  $qry = "UPDATE attributi SET nome='$nome' WHERE idattributo=$idattributo;";
	  $error = esegui_queryUpd($qry);
	  $conn->Execute("DELETE FROM attributi_categorie WHERE idattributo=$idattributo;");
	  foreach($cids as $cid) {
	  		$conn->Execute("INSERT INTO attributi_categorie VALUES($idattributo,$cid)");
	  	}
	  return $error;
	}
	
	function delAttributo($idattributo) {
	  global $conn;
	  $qry = "DELETE FROM attributi WHERE idattributo=$idattributo;";
	  $error = esegui_queryUpd($qry);
	  $qry = "DELETE FROM valore_attributo WHERE idattributo=$idattributo;";
	  $error = esegui_queryUpd($qry);
	  $qry = "DELETE FROM articolo_attributo WHERE idattributo=$idattributo;";
	  $error = esegui_queryUpd($qry);
	  $qry = "DELETE FROM attributi_categorie WHERE idattributo=$idattributo;";
	  $error = esegui_queryUpd($qry);
	  return $error;
	}
	
	function listValori($idattributo) {
	  $qry = "SELECT idvalore,valore FROM valore_attributo WHERE idattributo=$idattributo AND valore LIKE '%[%' UNION 
	  (SELECT idvalore,valore FROM valore_attributo WHERE idattributo=$idattributo AND valore NOT LIKE '%[%' ORDER BY cast(valore as unsigned));";
	  $rs = esegui_queryRs($qry);
	  if($rs->RecordCount()>0) {
		$result = '<table class="content" cellpadding="2" width="400">
						<tr>
						  <td class="error" colspan="3" align="center">ELENCO VALORI PER ATTRIBUTO</td>
						</tr>';
		while(!$rs->EOF) {
		  $result .= '<tr>
		  				<td width="300"><div id="edit_val_'.$rs->Fields("idvalore").'">'.$rs->Fields("idvalore").':'.utf8_encode($rs->Fields("valore")).'</div></td>
		  				<td align="center"><a href="javascript:;" onClick="editValore('.$rs->Fields("idvalore").','.$idattributo.');"><img src="imgs/ico_edit.gif" border="0"></a>&nbsp;&nbsp;<a href="javascript:;" onClick="delValore('.$rs->Fields("idvalore").','.$idattributo.');;"><img src="imgs/ico_delete.gif" border="0"></a></td>
		  			  </tr>';
		  $rs->MoveNext();
		}
		$result .= '</table>';
		$rs->Close();
	  } else
	  	  $result = '';
	  return $result;
	}
	
	function saveValore($idattributo,$valore,$start,$end,$passo) {
	  global $conn;
	  if($valore!="") {
		  $valore = addslashes($valore);
		  $qry = "INSERT INTO valore_attributo VALUES(NULL,$idattributo,'$valore');";
		  //die($qry);
		  $error = esegui_queryInsert($qry);
		  if($error>0)
		    return $error;
		  else
		    return 0;	
	  } else {
	  	  $passo=="0" ? $passo = 0.01 : $passo = str_replace(",",".",$passo);
	  	  $start = floatval($start);
	  	  $end = floatval($end);
	  	  $passo = floatval($passo);
	  	  if($start > 0 && $end > 0 && $start < $end) {
	  	  	for($i=$start;$i<=$end;$i+=$passo) {
	  	  		$qry = "INSERT INTO valore_attributo VALUES(NULL,$idattributo,'$i');";
		  		$error = esegui_queryInsert($qry);
	  	  	}
	  	  } else 
	  	  	  return "Devi inserire i valori corretti per il range";
	  }
	}
	
	function getValore($idattributo) {
		global $conn;
		$qry = "SELECT * FROM valore_attributo WHERE idvalore=$idvalore;";
		$arr = esegui_query($qry);
		$json = get_json($qry);
		return $json;	
	}
	
	function updValore($idvalore,$valore) {
	  global $conn;
	  $valore = addslashes($valore);
	  $qry = "UPDATE valore_attributo SET valore='$valore' WHERE idvalore=$idvalore;";
	  $error = esegui_queryUpd($qry);
	  return $error;
	}
	
	function delValore($idvalore) {
	  global $conn;
	  $qry = "DELETE FROM valore_attributo WHERE idvalore=$idvalore;";
	  $error = esegui_queryUpd($qry);
	  return $error;
	}
	
	function getCampiRicerca($newArt,$cid) {
	  global $conn;
	  $qry = "SELECT DISTINCT a.idattributo as idattributo,a.nome as nome FROM attributi a left join attributi_categorie c 
	  on a.idattributo=c.idattributo WHERE c.cid=$cid ORDER BY a.idattributo;";
	  $rs = esegui_queryRs($qry);
	  if($rs->RecordCount()>0) {
	    $content = '<table class="content" width="500" cellpadding="2">
						<tr>
						  <td colspan="2" align="center" class="error">VARIANTI</td>
						</tr>';
		while(!$rs->EOF) {
		  $content .= '<tr>
		  					<td width="200" align="right">'.$rs->Fields("nome").'</td>
		  					<td>
		  					<select name="varianti[]" multiple="multiple" size="10">';
		  $qry = "SELECT valore,idvalore FROM valore_attributo WHERE idattributo=".$rs->Fields("idattributo")." ORDER BY valore;";
		  $rsval = esegui_queryRs($qry);
		  if(!is_null($newArt))
		    $valore = $newArt->getIdValore($rs->Fields("idattributo"));
		  else
		    $valore = array();
		  if($rsval->RecordCount()>0) {
		  	while(!$rsval->EOF) {
		  		$content .= '<option value="'.$rs->Fields("idattributo").':'.$rsval->Fields("idvalore").'"';
		  		if(in_array($rsval->Fields("idvalore"),$valore)) $content .= ' selected';
		  		$content .= '>'.$rsval->Fields("valore").'</option>';
		  		$rsval->MoveNext();
		  	}
		  }
		  $content .= '</select>
		  </td>
		  			</tr>';
		  $rs->MoveNext();
		}
	    $content .= '</table>';
		$rs->Close();	
	  }
	  return $content;
	}
	
	function getCategorie($idattributo="") {
		global $conn;
		if($idattributo!="") $where = "WHERE a.idattributo=$idattributo";
		$qry = "SELECT DISTINCT a.cid as cid,c.titolo as titolo FROM attributi_categorie a left join categorie c 
		ON a.cid=c.cid $where ORDER BY titolo;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0) {
			$cats = array();
			while(!$rs->EOF) {
				array_push($cats,category::getPathCategoria($rs->Fields("cid"),$rs->Fields("titolo")));
				$rs->MoveNext();
			}
			$rs->Close();
			$result = json_encode($cats);
		}
		return $result;
	}
	
	function getCategorieFull() {
		global $conn;
		$qry = "SELECT DISTINCT c.cid as cid,c.titolo AS cat FROM `categorie` c WHERE c.idfather=2 ORDER BY titolo;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0) {
			$cats = array();
			while(!$rs->EOF) {
				array_push($cats,(object) array("cid"=>$rs->Fields("cid"),"titolo"=>category::getPathCategoria($rs->Fields("cid"),$rs->Fields("cat"))));
				$rs->MoveNext();
			}
			$rs->Close();
			$result = json_encode($cats);
		}
		return $result;
	}
}
?>